diff --git a/concore_cli/commands/validate.py b/concore_cli/commands/validate.py index 2cbefc7..c1a9eff 100644 --- a/concore_cli/commands/validate.py +++ b/concore_cli/commands/validate.py @@ -7,6 +7,11 @@ from ._source_dir import resolve_source_dir +# Mirrors mkconcore.py's safe_name (allow_path=False / allow_path=True) +_UNSAFE_NAME_RE = re.compile(r'[\x00-\x1F\x7F\\/:*?"<>|;&`$\'() ]') +_UNSAFE_PATH_RE = re.compile(r'[\x00-\x1F\x7F*?"<>|;&`$\'()]') +_KNOWN_EXTENSIONS = (".py", ".cpp", ".m", ".v", ".java", ".jl", ".sh") + def _classify_message(message, bucket_name): if bucket_name == "info": @@ -44,6 +49,12 @@ def _classify_message(message, bucket_name): "contains unsafe shell characters" ): return {"error_type": "unsafe_node_label"} + if message.startswith("Node '") and message.endswith("has empty container name"): + return {"error_type": "invalid_node_container_name"} + if message.startswith("Node container name '") and "contains spaces" in message: + return {"error_type": "invalid_node_container_name"} + if message.startswith("Node '") and "has unsafe source path" in message: + return {"error_type": "unsafe_source_path"} if message.startswith("Node '") and "missing format 'ID:filename'" in message: return {"error_type": "invalid_node_label_format"} if message.startswith("Node '") and message.endswith("has invalid format"): @@ -68,6 +79,11 @@ def _classify_message(message, bucket_name): return {"error_type": "missing_edge_target"} if message.startswith("Edge label '") and "has more than one source" in message: return {"error_type": "edge_label_multiple_sources"} + if message.startswith("Edge label '") and ( + "contains spaces" in message + or message.endswith("contains unsafe shell characters") + ): + return {"error_type": "unsafe_edge_label"} if message == "Workflow contains cycles (expected for control loops)": return {"error_type": "cycle_detected"} if message.startswith("Invalid port number:"): @@ -105,6 +121,75 @@ def _build_entries(bucket_name, messages, source_nodes): return entries +def _validate_source_path(label, filename): + """Validate relative source path rules matching mkconcore.py's safe_relpath.""" + normalized = filename.replace("\\", "/") + if normalized.startswith("/") or normalized.startswith("~"): + return ( + f"Node '{label}' has unsafe source path '{filename}': " + "absolute paths are not allowed" + ) + if re.match(r"^[A-Za-z]:", normalized) or ":" in normalized: + return ( + f"Node '{label}' has unsafe source path '{filename}': " + "drive paths and ':' are not allowed" + ) + if any(part in ("", "..") for part in normalized.split("/")): + return ( + f"Node '{label}' has unsafe source path '{filename}': invalid path segment" + ) + return None + + +def _validate_node_label( + label, node_id, exec_type, source_root, source_nodes, errors, warnings +): + """Validate a node's 'container:source' label against mkconcore build rules.""" + if _UNSAFE_PATH_RE.search(label) or "\\" in label: + errors.append(f"Node '{label}' contains unsafe shell characters") + return + + if ":" not in label: + warnings.append(f"Node '{label}' missing format 'ID:filename'") + return + + node_id_part, filename = label.split(":", 1) + if not node_id_part: + errors.append(f"Node '{label}' has empty container name") + elif " " in node_id_part: + errors.append( + f"Node container name '{node_id_part}' contains spaces (use '_' instead)" + ) + elif _UNSAFE_NAME_RE.search(node_id_part): + errors.append(f"Node '{label}' contains unsafe shell characters") + + # A node with no filename ('IN:' / 'OUT:') is a port-only endpoint. + if not filename: + return + + source_nodes[filename] = node_id + path_error = _validate_source_path(label, filename) + if path_error: + errors.append(path_error) + return + + if exec_type in ("posix", "windows") and "." not in filename: + errors.append( + f"Node '{label}' is a pulled container (no file " + f"extension); pulled containers need --type docker, " + f"not {exec_type}" + ) + return + + if "." in filename and not any(filename.endswith(ext) for ext in _KNOWN_EXTENSIONS): + warnings.append(f"Node '{label}' has unusual file extension") + + if "." in filename and source_root.exists(): + file_path = source_root / filename + if not file_path.exists(): + errors.append(f"Missing source file: {filename}") + + def _build_payload(workflow_path, source_root, errors, warnings, info, source_nodes): error_entries = _build_entries("errors", errors, source_nodes) warning_entries = _build_entries("warnings", warnings, source_nodes) @@ -239,55 +324,15 @@ def finalize(): if label_tag and label_tag.text: label = label_tag.text.strip() node_labels.append(label) - - # reject shell metacharacters to prevent command injection (#251) - if re.search(r'[;&|`$\'"()\\]', label): - errors.append( - f"Node '{label}' contains unsafe shell characters" - ) - continue - - if ":" not in label: - warnings.append(f"Node '{label}' missing format 'ID:filename'") - else: - parts = label.split(":") - if len(parts) != 2: - warnings.append(f"Node '{label}' has invalid format") - else: - nodeId_part, filename = parts - # A node with no filename ('IN:' / 'OUT:') is a - # port-only input/output source: nothing to check. - if filename: - source_nodes[filename] = node_id - if ( - exec_type in ("posix", "windows") - and "." not in filename - ): - errors.append( - f"Node '{label}' is a pulled container (no file " - f"extension); pulled containers need --type docker, " - f"not {exec_type}" - ) - elif not any( - filename.endswith(ext) - for ext in [ - ".py", - ".cpp", - ".m", - ".v", - ".java", - ".jl", - ] - ): - warnings.append( - f"Node '{label}' has unusual file extension" - ) - elif source_root.exists(): - file_path = source_root / filename - if not file_path.exists(): - errors.append( - f"Missing source file: {filename}" - ) + _validate_node_label( + label, + node_id, + exec_type, + source_root, + source_nodes, + errors, + warnings, + ) else: warnings.append(f"Node {node_id} has no label") except Exception as e: @@ -341,11 +386,24 @@ def finalize(): edge_label = label_tag.text.strip() if edge_label_regex.match(edge_label): zmq_edges += 1 + if _UNSAFE_NAME_RE.search(edge_label): + errors.append( + f"Edge label '{edge_label}' contains unsafe shell characters" + ) else: file_edges += 1 - label_sources.setdefault(edge_label, set()).add( - edge.get("source") - ) + if " " in edge_label: + errors.append( + f"Edge label '{edge_label}' contains spaces (use '_' instead)" + ) + elif _UNSAFE_NAME_RE.search(edge_label): + errors.append( + f"Edge label '{edge_label}' contains unsafe shell characters" + ) + else: + label_sources.setdefault(edge_label, set()).add( + edge.get("source") + ) except Exception: pass diff --git a/tests/test_validate_name_parity.py b/tests/test_validate_name_parity.py new file mode 100644 index 0000000..74425ea --- /dev/null +++ b/tests/test_validate_name_parity.py @@ -0,0 +1,135 @@ +import json +import pytest +from click.testing import CliRunner + +from concore_cli.cli import cli + +GRAPH_TEMPLATE = """ + + + {node_a} + {node_b} + {edge} + + +""" + + +def _invoke_validate( + tmp_path, node_a, edge, *extra, node_b="plant:b.py", files=("a.py", "b.py") +): + src = tmp_path / "src" + src.mkdir(exist_ok=True) + for rel in files: + target = src / rel + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("x = 1\n", encoding="utf-8") + wf = tmp_path / "wf.graphml" + wf.write_text( + GRAPH_TEMPLATE.format(node_a=node_a, node_b=node_b, edge=edge), + encoding="utf-8", + ) + return CliRunner().invoke(cli, ["validate", str(wf), "--source", str(src), *extra]) + + +def test_validate_rejects_spaces_in_node_container_name(tmp_path): + res = _invoke_validate(tmp_path, "my ctrl:a.py", "u", "--format", "json") + assert res.exit_code == 1 + payload = json.loads(res.output) + assert payload["valid"] is False + assert payload["errors"][0]["error_type"] == "invalid_node_container_name" + assert "use '_' instead" in payload["errors"][0]["message"] + + +def test_validate_rejects_slash_and_empty_container_name(tmp_path): + for node_label in ("a/b:a.py", ":a.py"): + res = _invoke_validate(tmp_path, node_label, "u", "--format", "json") + assert res.exit_code == 1, node_label + payload = json.loads(res.output) + assert payload["valid"] is False + + +@pytest.mark.parametrize( + "node_label", + [ + "ctrl:../evil.py", + "ctrl:/etc/passwd.py", + "ctrl:~/a.py", + "ctrl:C:/a.py", + "ctrl:a:b.py", + "ctrl:sub/", + ], +) +def test_validate_rejects_unsafe_source_paths(tmp_path, node_label): + res = _invoke_validate(tmp_path, node_label, "u", "--format", "json") + assert res.exit_code == 1, node_label + payload = json.loads(res.output) + assert payload["valid"] is False + assert any(e["error_type"] == "unsafe_source_path" for e in payload["errors"]) + + +def test_validate_allows_relative_subdir_source(tmp_path): + res = _invoke_validate( + tmp_path, + "ctrl:sub/a.py", + "u", + files=("sub/a.py", "b.py"), + ) + assert res.exit_code == 0, res.output + + +@pytest.mark.parametrize( + "edge_label", + [ + "my edge", + "../out", + "a/b", + "a:b", + "a;rm", + "a*b", + "0x1000_portA extra", + ], +) +def test_validate_rejects_unsafe_edge_labels(tmp_path, edge_label): + res = _invoke_validate(tmp_path, "ctrl:a.py", edge_label, "--format", "json") + assert res.exit_code == 1, edge_label + payload = json.loads(res.output) + assert payload["valid"] is False + assert any(e["error_type"] == "unsafe_edge_label" for e in payload["errors"]) + + +def test_validate_allows_valid_zmq_edge_label(tmp_path): + res = _invoke_validate(tmp_path, "ctrl:a.py", "0x1000_port_a") + assert res.exit_code == 0, res.output + + +def test_validate_supports_sh_and_checks_missing_unusual_ext(tmp_path): + ok_res = _invoke_validate( + tmp_path, + "ctrl:run.sh", + "u", + "--format", + "json", + files=("run.sh", "b.py"), + ) + assert ok_res.exit_code == 0, ok_res.output + ok_payload = json.loads(ok_res.output) + assert not any( + w["error_type"] == "unusual_file_extension" for w in ok_payload["warnings"] + ) + + bad_res = _invoke_validate( + tmp_path, + "ctrl:missing.rb", + "u", + "--format", + "json", + files=("b.py",), + ) + assert bad_res.exit_code == 1 + bad_payload = json.loads(bad_res.output) + assert any( + w["error_type"] == "unusual_file_extension" for w in bad_payload["warnings"] + ) + assert any(e["error_type"] == "missing_source_file" for e in bad_payload["errors"])