rsnarsna
feat(security,codegen): Wave 2-5 node standardization, SSRF & AST hardening (DEC-015)
a724795 Download lambdas/codegen/emitters_control_oop.py from Rsnarsna/auto: direct link, hf CLI and curl.
- Browser
- Download file 9.83 kB
-
https://huggingface.co/spaces/Rsnarsna/auto/resolve/main/lambdas/codegen/emitters_control_oop.py
- Command line
-
hf download hf://spaces/Rsnarsna/auto/lambdas/codegen/emitters_control_oop.py
-
curl -L -o emitters_control_oop.py https://huggingface.co/spaces/Rsnarsna/auto/resolve/main/lambdas/codegen/emitters_control_oop.py
9.83 kB
| """ | |
| ALLI Codegen Subpackage: Control Flow, Functions & Loop Emitters. | |
| """ | |
| import ast | |
| import re | |
| from typing import Optional, Tuple | |
| from language_core.codegen_contracts import ( | |
| BANNED_IMPORTS, DANGEROUS_CALLABLES, DANGEROUS_SPECIAL_ATTRS, RESTRICTED_HOST_MODULES, | |
| SAFE_RUNTIME_STDLIB_MODULES, STANDARD_LIBS, format_literal, sanitize_identifier, | |
| ) | |
| from language_core.nodes.loader import parse_safe_literal_or_json | |
| from lambdas.codegen.context import NodeCodegenCtx | |
| from lambdas.codegen.emitters_strings_oop import emit_string_and_oop_node, emit_module_and_fallback_node | |
| _IDENT_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$") | |
| ALLOWED_EXCEPTIONS = { | |
| "Exception", "ValueError", "TypeError", "KeyError", "IndexError", | |
| "ZeroDivisionError", "RuntimeError", "AttributeError", "FileNotFoundError", | |
| "IOError", "ArithmeticError", "LookupError", "AssertionError", "OverflowError" | |
| } | |
| def emit_control_and_functions_node(nctx: NodeCodegenCtx) -> Tuple[bool, Optional[str]]: | |
| raw_type, node_id, safe_id, params, cg = nctx.raw_type, nctx.node_id, nctx.safe_id, nctx.params, nctx.cg | |
| lines, ovm = cg.code_body_lines, cg.output_var_map | |
| if raw_type in ("control.if_else", "if_else") or "condition" in raw_type or raw_type == "if": | |
| cond_expr = nctx.resolve_input("condition", params.get("condition", True)) | |
| then_expr = nctx.resolve_input("then_val", format_literal(params.get("default_then", params.get("then_val", "True")))) | |
| else_expr = nctx.resolve_input("else_val", format_literal(params.get("default_else", params.get("else_val", "False")))) | |
| nv, bv = f"selected_{safe_id}", f"branch_{safe_id}" | |
| lines.extend([f" if {cond_expr}:", f" {nv} = {then_expr}", f' {bv} = "then"', " else:", f" {nv} = {else_expr}", f' {bv} = "else"']) | |
| ovm.update({f"{node_id}:selected": nv, f"{node_id}:then": nv, f"{node_id}:else": nv, f"{node_id}:result": nv, f"{node_id}:val": nv, f"{node_id}:out": nv, f"{node_id}:branch": bv, f"{node_id}:branch_taken": bv, node_id: nv}) | |
| return True, nv | |
| if raw_type in ("control.for_loop", "for_loop"): | |
| raw_lvar = str(params.get("loop_var", params.get("iterator_var", "i"))).strip() | |
| loop_var = sanitize_identifier(raw_lvar, "i") | |
| if not _IDENT_RE.match(loop_var) or loop_var.startswith("__"): | |
| loop_var = "i" | |
| iter_in = nctx.resolve_input("iterable", None) | |
| if iter_in and iter_in != "None": | |
| if not iter_in.strip().startswith(("[", "(", "{", "range(")): | |
| cg.discovered_modules.add("ast") | |
| iter_expr = f"(ast.literal_eval({iter_in}) if isinstance({iter_in}, str) else {iter_in})" | |
| else: | |
| iter_expr = iter_in | |
| elif params.get("iterable") is not None: | |
| ok_it, parsed_it = parse_safe_literal_or_json(params.get("iterable")) | |
| iter_expr = repr(parsed_it) if ok_it else format_literal(params.get("iterable")) | |
| else: | |
| r_start = int(params.get("range_start", 0) or 0) | |
| r_stop = int(params.get("range_stop", params.get("range_count", 5)) or 5) | |
| r_step = int(params.get("range_step", 1) or 1) | |
| iter_expr = f"range({r_start}, {r_stop}, {r_step})" | |
| nv = f"items_{safe_id}" | |
| lines.extend([f" {nv} = []", f" for {loop_var} in {iter_expr}:", f" {nv}.append({loop_var})"]) | |
| ovm.update({f"{node_id}:items": nv, f"{node_id}:iteration_count": f"len({nv})", f"{node_id}:completed": "True", f"{node_id}:result": nv, f"{node_id}:out": nv, node_id: nv}) | |
| return True, nv | |
| if raw_type in ("control.while_loop", "while_loop"): | |
| eff = {**nctx.data, **params} | |
| init_expr = nctx.resolve_input("initial_value", eff.get("initial_value", 0)) | |
| nv, iv = f"val_{safe_id}", f"iters_{safe_id}" | |
| cond_op = eff.get("operator", eff.get("condition_op", "<")) | |
| cond_op = cond_op if cond_op in ("<", "<=", ">", ">=", "==", "!=") else "<" | |
| try: | |
| thresh_num = float(eff.get("condition_val", eff.get("compare_value", eff.get("threshold", 5)))) | |
| thresh = int(thresh_num) if thresh_num.is_integer() else thresh_num | |
| except (ValueError, TypeError): | |
| thresh = 5 | |
| try: | |
| max_it = min(max(1, int(eff.get("max_iterations", 10) or 10)), 10000) | |
| except (ValueError, TypeError): | |
| max_it = 10 | |
| try: | |
| step_num = float(eff.get("step", eff.get("step_value", 1))) | |
| step_v = int(step_num) if step_num.is_integer() else step_num | |
| if step_v == 0: | |
| step_v = 1 | |
| except (ValueError, TypeError): | |
| step_v = 1 | |
| if str(eff.get("loop_mode", "while")).lower() == "do_while": | |
| lines.extend([ | |
| f" {nv} = {init_expr}", | |
| f" {iv} = 0", | |
| " while True:", | |
| f" {nv} += {step_v}", | |
| f" {iv} += 1", | |
| f" if not ({nv} {cond_op} {thresh} and {iv} < {max_it}):", | |
| " break", | |
| ]) | |
| else: | |
| lines.extend([ | |
| f" {nv} = {init_expr}", | |
| f" {iv} = 0", | |
| f" while {nv} {cond_op} {thresh} and {iv} < {max_it}:", | |
| f" {nv} += {step_v}", | |
| f" {iv} += 1", | |
| ]) | |
| ovm.update({f"{node_id}:final_value": nv, f"{node_id}:iterations": iv, f"{node_id}:completed": "True", f"{node_id}:body": nv, f"{node_id}:done": "True", f"{node_id}:result": nv, f"{node_id}:out": nv, node_id: nv}) | |
| return True, nv | |
| if raw_type in ("control.loop_control", "loop_control"): | |
| act = str(params.get("action", "break")).lower() | |
| act = act if act in ("break", "continue", "pass") else "break" | |
| nv = f"signal_{safe_id}" | |
| lines.append(f" {nv} = {format_literal(act)}") | |
| ovm.update({f"{node_id}:signal": nv, f"{node_id}:action_taken": format_literal(act), node_id: nv}) | |
| return True, nv | |
| if raw_type in ("function.def", "func_def"): | |
| fn_name = sanitize_identifier(params.get("func_name", "my_func"), "my_func") | |
| if not _IDENT_RE.match(fn_name) or fn_name.startswith("__"): | |
| fn_name = "my_func" | |
| raw_params = str(params.get("params_list", params.get("params", "x"))).strip() | |
| clean_params = [] | |
| for p in raw_params.split(","): | |
| p_clean = p.strip() | |
| if p_clean and _IDENT_RE.match(p_clean) and not p_clean.startswith("__"): | |
| clean_params.append(p_clean) | |
| params_str = ", ".join(clean_params) if clean_params else "x" | |
| raw_return = str(params.get("return_expr", "x")).strip() | |
| if any(c in raw_return for c in ("\n", "\r", ";")): | |
| raw_return = "None" | |
| try: | |
| parsed_ret = ast.parse(raw_return, mode="eval") | |
| for subnode in ast.walk(parsed_ret): | |
| if isinstance(subnode, ast.Name) and (subnode.id in DANGEROUS_CALLABLES or subnode.id in RESTRICTED_HOST_MODULES): | |
| raw_return = "None" | |
| break | |
| if isinstance(subnode, ast.Attribute) and (subnode.attr.startswith("__") or subnode.attr in DANGEROUS_SPECIAL_ATTRS): | |
| raw_return = "None" | |
| break | |
| except Exception: | |
| raw_return = "None" | |
| lines.extend([f" def {fn_name}({params_str}):", f" return {raw_return}"]) | |
| ovm.update({f"{node_id}:func_name": format_literal(fn_name), f"{node_id}:callable_fn": fn_name, node_id: fn_name}) | |
| return True, fn_name | |
| if raw_type in ("function.call", "func_call"): | |
| fn_target = nctx.resolve_input("callable_fn", params.get("func_name", "my_func")) | |
| has_wire = any(str(inc.get("target_handle") or inc.get("targetHandle") or "").lower() in ("arg", "args", "arg_1") for inc in nctx.incoming) | |
| has_lit = any(k in params for k in ("arg", "arg_val")) or "arg" in nctx.node_inputs or "arg" in nctx.data | |
| if not has_wire and not has_lit: | |
| cg.diagnostics.append({"code": "ERR-ARG-MISSING", "severity": "error", "message": f"Function call on node '{nctx.label}' ({node_id}) port 'arg' is missing required argument.", "node_id": node_id, "port_id": "arg"}) | |
| fn_arg = nctx.resolve_input("arg", params.get("arg", "None")) | |
| nv = f"call_{safe_id}" | |
| lines.append(f" {nv} = {fn_target}({fn_arg})") | |
| ovm.update({f"{node_id}:result": nv, f"{node_id}:val": nv, f"{node_id}:out": nv, node_id: nv}) | |
| return True, nv | |
| if raw_type in ("control.try_except", "try_except"): | |
| try_val = nctx.resolve_input("try_val", "None") | |
| fb_val = nctx.resolve_input(["fallback_val", "default_fallback"], format_literal(params.get("default_fallback", params.get("fallback", "safe_fallback")))) | |
| raw_exc = str(params.get("expected_exception", params.get("exception_type", "Exception"))).strip() | |
| exc = raw_exc if raw_exc in ALLOWED_EXCEPTIONS else "Exception" | |
| nv, hv, ev = f"try_res_{safe_id}", f"has_err_{safe_id}", f"err_msg_{safe_id}" | |
| lines.extend([f" {hv} = False", f' {ev} = ""', " try:"]) | |
| if try_val == "None": | |
| lines.append(" raise ValueError('No try value provided')") | |
| else: | |
| lines.extend([f" {nv} = {try_val}", f" if {nv} is None:", " raise ValueError('Try value evaluated to None')"]) | |
| lines.extend([f" except {exc} as e:", f" {nv} = {fb_val}", f" {hv} = True", f" {ev} = str(e)"]) | |
| ovm.update({f"{node_id}:result": nv, f"{node_id}:has_error": hv, f"{node_id}:caught_error": ev, f"{node_id}:out": nv, node_id: nv}) | |
| return True, nv | |
| return False, None | |