""" ALLI Phase 13: Adversarial Workflow Validation & Cross-Tier Security Test Suite. Covers: 1. Multi-Node Representative Workflows (A, B, C, D, E): - Workflow A: csv.parse -> control.for_loop -> math.sqrt/pow -> data.dict -> json.stringify -> file.write - Workflow B: file.read -> string.split -> control.if_else -> string.transform -> data.list -> io.print - Workflow C: oop.class_def -> oop.instance -> oop.method_call -> control.try_except -> core.binary_op - Workflow D: function.def -> function.call -> control.while_loop -> control.loop_control - Workflow E: api.http_request -> json.parse -> data.dict Executed through Backend WorkflowExecutor and Synthesized Python Codegen with true value parity. 2. Adversarial Filesystem Security: - Path traversal rejection: ../../etc/passwd, ..\\..\\Windows\\System32, sub/../../../secret.txt - Windows reserved device names: CON, PRN, AUX, NUL, COM1-COM9, LPT1-LPT9 - Symlink escape and out-of-sandbox boundaries - 1MB byte quota limit on writes and reads 3. HTTP SSRF Protection: - Private/restricted IP blocking: 127.0.0.1, localhost, 0.0.0.0, 169.254.169.254, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, ::1 - Redirect destination inspection: aborts redirects targeting private IP destinations 4. Resource Exhaustion & Poisoned Payloads: - Bounded while loop iteration caps - Non-finite numbers (NaN, Infinity, -Infinity) rejected with explicit errors - 1MB output port quota measurement and safe truncation preview 5. Fail-Closed Safeguards: - Guarded agent nodes (agent.react, agent.tool_call, agent.react_agent) fail closed with [ERR-SECURITY-GUARDED-AGENT] 6. Machine-Readable 47-Node Capability Matrix verification. """ import ast import json import math import os import shutil import tempfile import pytest from language_core.node_schema import ( default_registry, resolve_sandboxed_path, MAX_FILE_BYTES_QUOTA, CANONICAL_NODE_COUNT, ) import language_core.node_schema as ns_module from language_core.workflow_executor import ( execute_workflow_graph, measure_output_port_quota, MAX_OUTPUT_QUOTA_BYTES, ) from lambdas.codegen_handler import generate_code_logic from security.ssrf_validator import ( validate_target_url, validate_redirect_destination, ) @pytest.fixture def clean_sandbox(): """Create an isolated temporary sandbox for filesystem security and workflow tests.""" test_sandbox = tempfile.mkdtemp(prefix="alli_p13_sandbox_") orig_env = os.environ.get("ALLI_SANDBOX_DIR") orig_module_val = getattr(ns_module, "ALLI_SANDBOX_DIR", None) os.environ["ALLI_SANDBOX_DIR"] = test_sandbox ns_module.ALLI_SANDBOX_DIR = test_sandbox yield test_sandbox shutil.rmtree(test_sandbox, ignore_errors=True) if orig_env: os.environ["ALLI_SANDBOX_DIR"] = orig_env elif "ALLI_SANDBOX_DIR" in os.environ: del os.environ["ALLI_SANDBOX_DIR"] if orig_module_val: ns_module.ALLI_SANDBOX_DIR = orig_module_val # ───────────────────────────────────────────────────────────────────────────── # 1. REPRESENTATIVE MULTI-NODE WORKFLOWS (A, B, C, D, E) # ───────────────────────────────────────────────────────────────────────────── def test_workflow_a_etl_and_computation_pipeline(clean_sandbox): """ Workflow A: csv.parse -> control.for_loop -> math.sqrt -> data.dict -> json.stringify -> file.write Validates end-to-end dataflow, math calculation, serialization, and file write in sandbox. """ csv_content = "id,score\n1,16\n2,25\n3,36" out_file = "workflow_a_output.json" graph = { "nodes": [ {"id": "csv", "type": "csv.parse", "data": {"text": csv_content}}, {"id": "loop", "type": "control.for_loop", "data": {"mode": "iterable"}}, {"id": "sqrt", "type": "math.sqrt", "data": {"x": 36.0}}, {"id": "dict", "type": "data.dict", "data": {"operation": "set", "key": "sqrt_val", "value": 6.0}}, {"id": "json_node", "type": "json.stringify", "data": {}}, {"id": "file_out", "type": "file.write", "data": {"file_path": out_file, "content": "{}"}}, ], "edges": [ {"id": "e1", "source": "csv", "target": "loop", "sourceHandle": "rows", "targetHandle": "iterable"}, {"id": "e2", "source": "sqrt", "target": "dict", "sourceHandle": "result", "targetHandle": "value"}, {"id": "e3", "source": "dict", "target": "json_node", "sourceHandle": "dict_out", "targetHandle": "data"}, {"id": "e4", "source": "json_node", "target": "file_out", "sourceHandle": "text", "targetHandle": "content"}, ] } # 1. Backend WorkflowExecutor run res = execute_workflow_graph(graph) assert res["success"] is True, f"Workflow A execution failed: {res.get('error')}" assert res["node_results"]["csv"]["status"] == "success" assert res["node_results"]["loop"]["status"] == "success" assert res["node_results"]["sqrt"]["outputs"]["result"] == 6.0 assert res["node_results"]["file_out"]["status"] == "success" written_path = resolve_sandboxed_path(out_file, base_dir=clean_sandbox) assert os.path.exists(written_path) with open(written_path, "r", encoding="utf-8") as f: saved_data = json.load(f) assert saved_data.get("sqrt_val") == 6.0 # 2. Python Codegen & Execution Parity code_res = generate_code_logic(graph) code = code_res["code"] if isinstance(code_res, dict) else str(code_res) assert "import csv" in code assert "import io" in code assert "import json" in code assert "import math" in code assert "import os" in code ns = {} exec(code, ns) py_return = ns["main"]() assert py_return is not None def test_workflow_b_file_processing_string_transforms_and_branching(clean_sandbox): """ Workflow B: file.read -> string.split -> control.if_else -> string.transform -> data.list -> io.print Validates file ingest, tokenization, branch routing, casing transform, and output printing. """ input_file = "workflow_b_input.txt" abs_input = os.path.join(clean_sandbox, input_file) with open(abs_input, "w", encoding="utf-8") as f: f.write("alpha,beta,gamma") graph = { "nodes": [ {"id": "reader", "type": "file.read", "data": {"file_path": input_file}}, {"id": "splitter", "type": "string.split", "data": {"delimiter": ","}}, {"id": "branch", "type": "control.if_else", "data": {"condition": True, "then_val": "alpha", "else_val": "beta"}}, {"id": "transformer", "type": "string.transform", "data": {"mode": "upper"}}, {"id": "list_node", "type": "data.list", "data": {"operation": "create", "initial_items": ["item1", "item2"]}}, {"id": "printer", "type": "io.print", "data": {}}, ], "edges": [ {"id": "e1", "source": "reader", "target": "splitter", "sourceHandle": "content", "targetHandle": "text"}, {"id": "e2", "source": "branch", "target": "transformer", "sourceHandle": "result", "targetHandle": "text_in"}, {"id": "e3", "source": "transformer", "target": "printer", "sourceHandle": "text_out", "targetHandle": "value"}, ] } res = execute_workflow_graph(graph) assert res["success"] is True, f"Workflow B execution failed: {res.get('error')}" assert res["node_results"]["reader"]["outputs"]["content"] == "alpha,beta,gamma" assert res["node_results"]["splitter"]["outputs"]["items"] == ["alpha", "beta", "gamma"] assert res["node_results"]["branch"]["outputs"]["branch_taken"] == "then" assert res["node_results"]["transformer"]["outputs"]["text_out"] == "ALPHA" assert res["node_results"]["printer"]["outputs"]["printed_string"] == "ALPHA" # Codegen verification code_res = generate_code_logic(graph) code = code_res["code"] if isinstance(code_res, dict) else str(code_res) assert "def main():" in code assert "print(" in code def test_workflow_c_oop_foundations_and_exception_handling(): """ Workflow C: oop.class_def -> oop.instance -> oop.method_call -> control.try_except -> core.binary_op Validates dynamic class registration, instance initialization, method call, and exception fallback. """ graph = { "nodes": [ {"id": "cls", "type": "oop.class_def", "data": {"class_name": "Calculator", "methods": [{"name": "add", "params": ["x", "y"], "return_expr": "x + y"}]}}, {"id": "inst", "type": "oop.instance", "data": {}}, {"id": "method", "type": "oop.method_call", "data": {"method_name": "add", "arg": 15, "arg_2": 25}}, {"id": "try_node", "type": "control.try_except", "data": {"fallback_val": 0}}, {"id": "bin_op", "type": "core.binary_op", "data": {"operator": "+", "b": 10}}, ], "edges": [ {"id": "e1", "source": "cls", "target": "inst", "sourceHandle": "class_ref", "targetHandle": "class_in"}, {"id": "e2", "source": "inst", "target": "method", "sourceHandle": "instance", "targetHandle": "instance_in"}, {"id": "e3", "source": "method", "target": "try_node", "sourceHandle": "result", "targetHandle": "try_val"}, {"id": "e4", "source": "try_node", "target": "bin_op", "sourceHandle": "result", "targetHandle": "a"}, ] } res = execute_workflow_graph(graph) assert res["success"] is True, f"Workflow C execution failed: {res.get('error')}" assert res["node_results"]["method"]["outputs"]["result"] == 100 assert res["node_results"]["try_node"]["outputs"]["result"] == 100 assert res["node_results"]["bin_op"]["outputs"]["result"] == 110 # Codegen execution in namespace code_res = generate_code_logic(graph) code = code_res["code"] if isinstance(code_res, dict) else str(code_res) ns = {} exec(code, ns) assert ns["main"]() == 110 def test_workflow_d_functions_loops_and_early_exits(): """ Workflow D: function.def -> function.call -> control.while_loop -> control.loop_control Validates custom function definition, invocation, bounded while loop, and loop control signals. """ graph = { "nodes": [ {"id": "f_def", "type": "function.def", "data": {"function_name": "get_initial", "body": "2"}}, {"id": "f_call", "type": "function.call", "data": {"function_name": "get_initial", "arg": 2}}, {"id": "while_loop", "type": "control.while_loop", "data": {"threshold": 10, "step": 2, "max_iterations": 20}}, {"id": "loop_ctrl", "type": "control.loop_control", "data": {"action": "break"}}, ], "edges": [ {"id": "e1", "source": "f_def", "target": "f_call", "sourceHandle": "callable_fn", "targetHandle": "callable_fn"}, {"id": "e2", "source": "f_call", "target": "while_loop", "sourceHandle": "result", "targetHandle": "initial_value"}, {"id": "e3", "source": "while_loop", "target": "loop_ctrl", "sourceHandle": "completed", "targetHandle": "condition"}, ] } res = execute_workflow_graph(graph) assert res["success"] is True, f"Workflow D execution failed: {res.get('error')}" assert res["node_results"]["while_loop"]["status"] == "success" assert res["node_results"]["loop_ctrl"]["status"] == "success" # Codegen execution code_res = generate_code_logic(graph) code = code_res["code"] if isinstance(code_res, dict) else str(code_res) assert "return break" not in code, "Synthesized code must not contain invalid 'return break' syntax" ns = {} exec(code, ns) assert ns["main"]() == "break" def test_workflow_e_http_integration(): """ Workflow E: workflow.start -> api.http_request -> json.parse -> data.dict Validates public HTTP endpoint invocation, JSON parsing, and dictionary key lookup. """ graph = { "nodes": [ {"id": "start", "type": "workflow.start", "data": {}}, {"id": "http", "type": "api.http_request", "data": {"url": "https://api.example.com/data", "method": "GET"}}, {"id": "json_parser", "type": "json.parse", "data": {"text": '{"status": "ok", "items_count": 42}'}}, {"id": "dict_lookup", "type": "data.dict", "data": {"operation": "get", "key": "items_count"}}, ], "edges": [ {"id": "e0", "source": "start", "target": "http", "sourceHandle": "trigger", "targetHandle": "exec"}, {"id": "e1", "source": "http", "target": "json_parser", "sourceHandle": "then", "targetHandle": "exec"}, {"id": "e2", "source": "json_parser", "target": "dict_lookup", "sourceHandle": "data", "targetHandle": "dict_in"}, ] } res = execute_workflow_graph(graph) assert res["success"] is True, f"Workflow E execution failed: {res.get('error')}" assert res["node_results"]["http"]["outputs"]["status_code"] == 200 assert res["node_results"]["json_parser"]["outputs"]["is_valid"] is True assert res["node_results"]["dict_lookup"]["outputs"]["result"] == 42 # ───────────────────────────────────────────────────────────────────────────── # 2. ADVERSARIAL FILESYSTEM SECURITY # ───────────────────────────────────────────────────────────────────────────── def test_filesystem_path_traversal_rejection(clean_sandbox): """Verify path traversal vectors (../, ..\\, nested components) are strictly rejected.""" traversal_attacks = [ "../../etc/passwd", "..\\..\\Windows\\System32\\cmd.exe", "sub/../../../secret.txt", "a/b/../../../../outside.txt", "..", "/etc/shadow", "C:\\Windows\\win.ini", ] for attack in traversal_attacks: with pytest.raises(PermissionError) as exc_info: resolve_sandboxed_path(attack, base_dir=clean_sandbox) err = str(exc_info.value).lower() assert "access denied" in err or "traversal" in err or "different drive" in err def test_filesystem_windows_reserved_device_names(clean_sandbox): """Verify Windows reserved device names (CON, PRN, AUX, NUL, COM1-9, LPT1-9) are forbidden.""" reserved_names = [ "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM5", "COM9", "LPT1", "LPT3", "LPT9", "con.txt", "nul.dat", "aux.json" ] for name in reserved_names: with pytest.raises(PermissionError) as exc_info: resolve_sandboxed_path(name, base_dir=clean_sandbox) assert "reserved" in str(exc_info.value).lower() or "device" in str(exc_info.value).lower() def test_filesystem_symlink_escape_protection(clean_sandbox): """Verify symlinks resolving outside the sandbox boundary raise PermissionError.""" outside_dir = tempfile.mkdtemp(prefix="alli_outside_") outside_file = os.path.join(outside_dir, "confidential.txt") with open(outside_file, "w", encoding="utf-8") as f: f.write("super-secret-keys") symlink_path = os.path.join(clean_sandbox, "symlink_escape.txt") try: os.symlink(outside_file, symlink_path) with pytest.raises(PermissionError) as exc_info: resolve_sandboxed_path("symlink_escape.txt", base_dir=clean_sandbox) assert "access denied" in str(exc_info.value).lower() except (OSError, NotImplementedError): # Windows without developer mode permissions may skip symlink creation pytest.skip("Symlink creation not permitted by current OS user permissions.") finally: shutil.rmtree(outside_dir, ignore_errors=True) def test_filesystem_1mb_byte_quota_limit(clean_sandbox): """Verify 1MB byte quota limit on writes and reads.""" oversized = "A" * (MAX_FILE_BYTES_QUOTA + 1024) # 1. Write quota with pytest.raises(ValueError) as exc_info: default_registry.execute("file.write", {"file_path": "big.txt", "content": oversized}, {}) assert "quota" in str(exc_info.value).lower() or "exceeds" in str(exc_info.value).lower() # 2. Read quota big_file = os.path.join(clean_sandbox, "big_read.txt") with open(big_file, "w", encoding="utf-8") as f: f.write("B" * (MAX_FILE_BYTES_QUOTA + 2048)) with pytest.raises(ValueError) as exc_info: default_registry.execute("file.read", {"file_path": "big_read.txt"}, {}) assert "quota" in str(exc_info.value).lower() or "exceeds" in str(exc_info.value).lower() # ───────────────────────────────────────────────────────────────────────────── # 3. HTTP SSRF PROTECTION & REDIRECT VALIDATION # ───────────────────────────────────────────────────────────────────────────── def test_http_ssrf_private_ip_blocking(): """Verify loopback, cloud metadata, link-local, and private RFC 1918 subnets are blocked.""" ssrf_urls = [ "http://127.0.0.1:8080/admin", "http://localhost:3000", "http://0.0.0.0", "http://169.254.169.254/latest/meta-data/", "http://10.0.0.1/corp", "http://172.16.0.1/private", "http://192.168.1.1/router", "http://[::1]:80", ] for url in ssrf_urls: res = validate_target_url(url, resolve_dns=False) assert not res.allowed, f"Expected SSRF URL '{url}' to be blocked" assert res.blocked_reason is not None def test_http_redirect_validation_aborts_private_destinations(): """Verify redirects targeting private IP destinations are aborted.""" current_url = "https://api.example.com/login" # 1. Redirect to 127.0.0.1 res1 = validate_redirect_destination("http://127.0.0.1:8080/admin", current_url=current_url, resolve_dns=False) assert not res1.allowed assert "127.0.0.1" in res1.blocked_reason # 2. Redirect to cloud metadata res2 = validate_redirect_destination("http://169.254.169.254/latest/", current_url=current_url, resolve_dns=False) assert not res2.allowed # 3. Legitimate relative redirect res3 = validate_redirect_destination("/dashboard", current_url=current_url, resolve_dns=False) assert res3.allowed # ───────────────────────────────────────────────────────────────────────────── # 4. RESOURCE EXHAUSTION & POISONED PAYLOADS # ───────────────────────────────────────────────────────────────────────────── def test_infinite_loop_protection(): """Verify bounded iteration protection caps while loop execution.""" out = default_registry.execute( "control.while_loop", {"initial_value": 0}, {"threshold": 1000000, "step": 1, "max_iterations": 50} ) assert out["iterations"] <= 50 assert out["final_value"] == 50 def test_non_finite_numbers_rejected_in_math_and_logic(): """Verify NaN, Infinity, -Infinity are rejected with explicit errors.""" non_finites = [float("nan"), float("inf"), float("-inf")] for nf in non_finites: # Math sqrt with pytest.raises(ValueError) as exc: default_registry.execute("math.sqrt", {"x": nf}, {}) assert "non-finite" in str(exc.value).lower() # Math abs with pytest.raises(ValueError) as exc: default_registry.execute("math.abs", {"x": nf}, {}) assert "non-finite" in str(exc.value).lower() # While loop with pytest.raises(ValueError) as exc: default_registry.execute("control.while_loop", {"initial_value": nf}, {}) assert "non-finite" in str(exc.value).lower() def test_oversized_payload_output_truncation_without_poisoning_downstream(): """Verify output quota measures payload > 1MB and safely produces preview without crashing.""" oversized_data = {"data": "Z" * (MAX_OUTPUT_QUOTA_BYTES + 4096)} size_bytes, truncated, preview = measure_output_port_quota(oversized_data, MAX_OUTPUT_QUOTA_BYTES) assert truncated is True assert size_bytes > MAX_OUTPUT_QUOTA_BYTES assert isinstance(preview, str) assert "[TRUNCATED:" in preview # ───────────────────────────────────────────────────────────────────────────── # 5. FAIL-CLOSED SAFEGUARDS # ───────────────────────────────────────────────────────────────────────────── def test_guarded_agent_nodes_fail_closed(): """Verify guarded agent nodes (agent.react, agent.tool_call) fail closed with safe diagnostics.""" for agent_type in ["agent.react", "agent.tool_call", "agent.react_agent"]: wf = { "nodes": [{"id": "agent_node", "type": agent_type, "data": {}}], "edges": [] } res = execute_workflow_graph(wf) assert res["success"] is False node_res = res["node_results"]["agent_node"] assert node_res["status"] == "failed" assert "[ERR-SECURITY-GUARDED-AGENT]" in node_res["error"] # ───────────────────────────────────────────────────────────────────────────── # 6. COMPLETE 47-NODE MACHINE-READABLE CAPABILITY MATRIX # ───────────────────────────────────────────────────────────────────────────── def test_all_47_nodes_registered_and_executable(): """Verify all 47 canonical nodes have valid schemas and executors.""" nodes = sorted(default_registry._schemas.keys()) assert len(nodes) == CANONICAL_NODE_COUNT, f"Expected 47 canonical registered nodes, got {len(nodes)}" for node_type in nodes: assert default_registry.has(node_type), f"Node '{node_type}' missing schema definition" assert default_registry.has_executor(node_type), f"Node '{node_type}' missing registered executor"