""" ALLI Codegen Subpackage: Safe Wave-1 Core & Workspace Env Emitters Eliminates raw code-string interpolation for type_cast, variable/constant literals, and emits AST-validated sys.env_get / sys.env_set statements. """ import re from typing import Any, Optional, Tuple from lambdas.codegen.context import NodeCodegenCtx from language_core.codegen_contracts import format_literal, sanitize_identifier from language_core.executor.wave1_handlers import normalize_cast_target from language_core.workspace_env_contracts import validate_env_key SAFE_HTTP_METHODS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}) SAFE_BINARY_OPS = frozenset({"+", "-", "*", "/", "//", "%", "**"}) SAFE_COMPARE_OPS = frozenset({"==", "!=", "<", "<=", ">", ">="}) SAFE_LOGICAL_OPS = frozenset({"and", "or", "not"}) SAFE_ROUNDING_MODES = frozenset({"none", "round", "floor", "ceil"}) _ENCODING_RE = re.compile(r"^[a-zA-Z0-9_-]{2,24}$") def sanitize_encoding_name(raw_enc: Any, default: str = "utf-8") -> str: """Validate text encoding identifier strictly to prevent string interpolation escape.""" candidate = str(raw_enc or default).strip() return candidate if _ENCODING_RE.match(candidate) else default def validate_safe_op(raw_op: Any, allowed: frozenset, default: str, nctx: NodeCodegenCtx, kind: str) -> str: """Allowlist operator string cleanly before code interpolation.""" op = str(raw_op or default).strip() if op not in allowed: nctx.cg.diagnostics.append({ "code": "CODEGEN-SECURITY-VIOLATION", "severity": "error", "message": f"Unsafe {kind} operator '{op}' rejected on node '{nctx.label}' ({nctx.node_id}).", "node_id": nctx.node_id, }) return default return op def emit_safe_constant_node(nctx: NodeCodegenCtx) -> Tuple[bool, Optional[str]]: """Emit literal constant assignment supporting both literal_value and value aliases.""" raw_type, node_id, safe_id, params, cg = nctx.raw_type, nctx.node_id, nctx.safe_id, nctx.params, nctx.cg lines = cg.code_body_lines raw_val = params.get("literal_value") if raw_val is None: raw_val = params.get("value", 0) ctype = str(params.get("const_type") or "").strip().lower() _tmap = ( ("int", "int"), ("integer", "int"), ("float", "float"), ("number", "float"), ("str", "str"), ("string", "str"), ("text", "str"), ("bool", "bool"), ("boolean", "bool"), ("list", "list"), ("dict", "dict"), ) dtype = ctype if ctype in ("int", "float", "str", "bool", "list", "dict", "any") else next((v for k, v in _tmap if k in raw_type), "any") try: formatted_val = format_literal(raw_val, dtype) except ValueError as ve: cg.diagnostics.append({"code": "VAL-NON-FINITE-NUMBER", "severity": "error", "message": f"Node '{nctx.label}' ({node_id}): {ve}", "node_id": node_id}) formatted_val = "0.0" nv = sanitize_identifier(params.get("const_name"), f"val_{safe_id}") lines.append(f" {nv} = {formatted_val}") return True, nv def emit_safe_variable_node(nctx: NodeCodegenCtx) -> Tuple[bool, Optional[str]]: """Emit variable assignment preserving explicit type annotations and upstream input overrides.""" params, safe_id, cg = nctx.params, nctx.safe_id, nctx.cg nv = sanitize_identifier(params.get("var_name", "my_var"), f"var_{safe_id}") default_val = params.get("literal_value") if params.get("literal_value") is not None else params.get("value", 0) vtype = str(params.get("var_type") or ("str" if isinstance(default_val, str) and not default_val.lstrip("-").isdigit() else "int")).lower() if nctx.incoming: assigned = nctx.resolve_input(["in_val", "in", "val", "value"], default_val) else: assigned = format_literal(default_val, vtype) cg.code_body_lines.append(f" {nv} = {assigned}") return True, nv def emit_safe_type_cast(nctx: NodeCodegenCtx) -> Tuple[bool, Optional[str]]: """Emit AST-safe explicit type conversion with strict target_type allowlisting (zero code injection).""" node_id, safe_id, params, cg = nctx.node_id, nctx.safe_id, nctx.params, nctx.cg lines, nv = cg.code_body_lines, f"cast_{safe_id}" raw_target = params.get("target_type", "str") try: ttype = normalize_cast_target(raw_target) except ValueError as exc: cg.diagnostics.append({ "code": "CODEGEN-SECURITY-VIOLATION", "severity": "error", "message": str(exc), "node_id": node_id, "port_id": "target_type", }) lines.append(f" {nv} = None") return True, nv val_expr = nctx.resolve_input(["value", "in_val", "val", "raw"], params.get("value", 0)) if ttype == "bool": lines.append(f" {nv} = (({val_expr}).strip().lower() in ('true', '1', 'yes', 'on') if isinstance({val_expr}, str) else bool({val_expr}))") elif ttype == "json": cg.discovered_modules.add("json") lines.append(f" {nv} = (json.loads({val_expr}) if isinstance({val_expr}, str) else json.dumps({val_expr}))") else: lines.append(f" {nv} = {ttype}({val_expr})") return True, nv def emit_safe_sys_env(nctx: NodeCodegenCtx) -> Tuple[bool, Optional[str]]: """Emit clean Python os.getenv / os.environ[KEY] code for workspace env nodes.""" 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 not in ("alli.sys.env", "sys.env_get", "sys.env", "sys.env_set"): return False, None is_set_mode = raw_type == "sys.env_set" or (raw_type in ("sys.env", "alli.sys.env") and str(params.get("mode") or "get").strip().lower() == "set") raw_key = str(params.get("key") or ("APP_CONFIG_VAR" if is_set_mode else "ENV_VAR")).strip() ok_key, clean_key_or_code, key_err = validate_env_key(raw_key) if not ok_key: cg.diagnostics.append({ "code": clean_key_or_code, "severity": "error", "message": key_err, "node_id": node_id, "port_id": "key", }) return True, f"env_err_{safe_id}" cg.discovered_modules.add("os") cg.referenced_env_keys.add(clean_key_or_code) key_lit = format_literal(clean_key_or_code) is_secret = bool(params.get("is_secret")) if is_set_mode: if nctx.is_wired(["value", "val", "in"]): val_expr = nctx.resolve_input(["value", "val", "in"], "") lines.append(f" os.environ[{key_lit}] = str({val_expr})") elif is_secret: lines.append(f" os.environ[{key_lit}] = os.getenv({key_lit}, \"\")") else: raw_val = nctx.node_inputs.get("value") if "value" in nctx.node_inputs else params.get("value") val_expr = format_literal(raw_val if raw_val is not None else "") lines.append(f" os.environ[{key_lit}] = str({val_expr})") nv = f"env_set_{safe_id}" lines.append(f" {nv} = {key_lit}") ovm.update({f"{node_id}:result": nv, f"{node_id}:key": nv, f"{node_id}:out": nv, node_id: nv}) return True, nv def_val = "" if is_secret else (params.get("default_val") if params.get("default_val") is not None else "") def_expr = format_literal(str(def_val)) nv = sanitize_identifier(params.get("var_name"), f"env_{safe_id}") lines.append(f" {nv} = os.getenv({key_lit}, {def_expr})") ovm.update({f"{node_id}:result": nv, f"{node_id}:val": nv, f"{node_id}:out": nv, node_id: nv}) return True, nv