lam-cli 0.1.4__tar.gz → 0.1.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lam-cli
3
- Version: 0.1.4
3
+ Version: 0.1.5
4
4
  Summary: Secure data transformation tool supporting JQ and JavaScript (Bun)
5
5
  Home-page: https://github.com/laminar-run/lam
6
6
  Author: Laminar Run, Inc.
@@ -3,6 +3,7 @@
3
3
  import json
4
4
  import logging
5
5
  import os
6
+ import re
6
7
  import shutil
7
8
  import socket
8
9
  import subprocess
@@ -87,6 +88,7 @@ class Stats:
87
88
  class EngineType(Enum):
88
89
  JQ = "jq"
89
90
  JAVASCRIPT = "js"
91
+ PYTHON = "py"
90
92
 
91
93
  class ProcessingError(Exception):
92
94
  """Custom exception for processing errors"""
@@ -441,11 +443,402 @@ class BunEngine(Engine):
441
443
  "type": e.__class__.__name__
442
444
  }, str(e)
443
445
 
446
+ class PythonEngine(Engine):
447
+ """Python execution engine with improved sandboxing for security"""
448
+ def __init__(self, *args, **kwargs):
449
+ super().__init__(*args, **kwargs)
450
+ self.modules_dir = Path(tempfile.gettempdir()) / "lam_python_modules"
451
+ self.modules_dir.mkdir(exist_ok=True)
452
+ # Define allowed modules that can be safely imported
453
+ self.allowed_modules = {
454
+ "json", "datetime", "math", "statistics", "collections",
455
+ "itertools", "functools", "re", "copy", "decimal",
456
+ "csv", "io", "dataclasses", "typing", "enum"
457
+ }
458
+
459
+ def validate_environment(self) -> bool:
460
+ logger.debug("Validating Python environment")
461
+ return sys.executable is not None
462
+
463
+ def create_safe_globals(self) -> dict:
464
+ """Create a restricted globals dictionary for safer execution"""
465
+ safe_globals = {
466
+ "__builtins__": {
467
+ # Safe builtins only
468
+ "abs": abs, "all": all, "any": any, "bool": bool,
469
+ "chr": chr, "dict": dict, "dir": dir, "divmod": divmod,
470
+ "enumerate": enumerate, "filter": filter, "float": float,
471
+ "format": format, "frozenset": frozenset, "hash": hash,
472
+ "hex": hex, "int": int, "isinstance": isinstance,
473
+ "issubclass": issubclass, "iter": iter, "len": len,
474
+ "list": list, "map": map, "max": max, "min": min,
475
+ "next": next, "oct": oct, "ord": ord, "pow": pow,
476
+ "print": print, "range": range, "repr": repr,
477
+ "reversed": reversed, "round": round, "set": set,
478
+ "slice": slice, "sorted": sorted, "str": str, "sum": sum,
479
+ "tuple": tuple, "type": type, "zip": zip,
480
+ # Add Exception types for error handling
481
+ "Exception": Exception, "ValueError": ValueError,
482
+ "TypeError": TypeError, "KeyError": KeyError,
483
+ "IndexError": IndexError
484
+ },
485
+ # Pre-import safe modules
486
+ "json": json,
487
+ "datetime": datetime,
488
+ "math": __import__("math"),
489
+ "statistics": __import__("statistics"),
490
+ "collections": __import__("collections"),
491
+ "itertools": __import__("itertools"),
492
+ "functools": __import__("functools"),
493
+ "re": __import__("re")
494
+ }
495
+ return safe_globals
496
+
497
+ def check_for_dangerous_code(self, code: str) -> Optional[str]:
498
+ """Check for potentially dangerous patterns in the code"""
499
+ dangerous_patterns = [
500
+ (r"__import__\s*\(", "Use of __import__ is not allowed"),
501
+ (r"eval\s*\(", "Use of eval() is not allowed"),
502
+ (r"exec\s*\(", "Use of exec() is not allowed"),
503
+ (r"globals\s*\(", "Access to globals() is not allowed"),
504
+ (r"locals\s*\(", "Access to locals() is not allowed"),
505
+ (r"getattr\s*\(", "Use of getattr() is not allowed"),
506
+ (r"setattr\s*\(", "Use of setattr() is not allowed"),
507
+ (r"delattr\s*\(", "Use of delattr() is not allowed"),
508
+ (r"compile\s*\(", "Use of compile() is not allowed"),
509
+ (r"open\s*\(", "Use of open() is not allowed"),
510
+ (r"__subclasses__", "Access to __subclasses__ is not allowed"),
511
+ (r"subprocess", "Access to subprocess module is not allowed"),
512
+ (r"sys\.", "Access to sys module is not allowed"),
513
+ (r"os\.", "Access to os module is not allowed"),
514
+ (r"shutil", "Access to shutil module is not allowed"),
515
+ (r"pathlib", "Access to pathlib module is not allowed"),
516
+ (r"importlib", "Access to importlib module is not allowed"),
517
+ (r"builtins", "Access to builtins module is not allowed"),
518
+ (r"_thread", "Access to _thread module is not allowed"),
519
+ (r"ctypes", "Access to ctypes module is not allowed"),
520
+ (r"socket", "Access to socket module is not allowed"),
521
+ (r"pickle", "Access to pickle module is not allowed"),
522
+ (r"multiprocessing", "Access to multiprocessing module is not allowed"),
523
+ (r"__\w+__", "Access to dunder attributes may not be allowed")
524
+ ]
525
+
526
+ for pattern, message in dangerous_patterns:
527
+ if re.search(pattern, code):
528
+ return message
529
+
530
+ # Check for imports outside of allowed modules
531
+ import_pattern = r"import\s+(\w+)|from\s+(\w+)\s+import"
532
+ for match in re.finditer(import_pattern, code):
533
+ module = match.group(1) or match.group(2)
534
+ if module and module not in self.allowed_modules:
535
+ return f"Import of '{module}' is not allowed, only these modules are permitted: {', '.join(sorted(self.allowed_modules))}"
536
+
537
+ return None
538
+
539
+ def create_wrapper(self, input_data: str, user_script: str) -> str:
540
+ """Create the wrapper script with proper escaping and sandboxing"""
541
+ # Perform safety checks before creating wrapper
542
+ safety_issue = self.check_for_dangerous_code(user_script)
543
+ if safety_issue:
544
+ # Return a wrapper that will immediately exit with the safety error
545
+ return f'''
546
+ import json
547
+ import sys
548
+
549
+ sys.stdout.write(json.dumps({{
550
+ "error": "Security violation detected: {safety_issue}",
551
+ "stack": []
552
+ }}))
553
+ sys.exit(1)
554
+ '''
555
+
556
+ return f'''
557
+ import json
558
+ import sys
559
+ import traceback
560
+ from datetime import datetime
561
+ import re
562
+ import math
563
+ import statistics
564
+ import collections
565
+ import itertools
566
+ import functools
567
+
568
+ # Resource limiting
569
+ import resource
570
+ import signal
571
+
572
+ # Set resource limits
573
+ def set_resource_limits():
574
+ # 5 seconds CPU time
575
+ resource.setrlimit(resource.RLIMIT_CPU, (5, 5))
576
+
577
+ # 100MB memory limit
578
+ memory_limit = 100 * 1024 * 1024 # 100MB in bytes
579
+ resource.setrlimit(resource.RLIMIT_AS, (memory_limit, memory_limit))
580
+
581
+ # Set timeout handler
582
+ def timeout_handler(signum, frame):
583
+ sys.stderr.write(json.dumps({{
584
+ "error": "Execution timed out (5 seconds)",
585
+ "stack": []
586
+ }}))
587
+ sys.exit(1)
588
+
589
+ signal.signal(signal.SIGALRM, timeout_handler)
590
+ signal.alarm(5) # 5 second timeout
591
+
592
+ try:
593
+ set_resource_limits()
594
+ except Exception as e:
595
+ # Continue if resource limiting is not available (e.g., on Windows)
596
+ pass
597
+
598
+ # Setup basic logging
599
+ logs = []
600
+
601
+ class LogCapture:
602
+ def __init__(self, log_type):
603
+ self.log_type = log_type
604
+
605
+ def write(self, message):
606
+ if message.strip():
607
+ logs.append({{"type": self.log_type, "message": message.strip()}})
608
+ return len(message)
609
+
610
+ def flush(self):
611
+ pass
612
+
613
+ # Custom safer importer
614
+ class RestrictedImporter:
615
+ def __init__(self, allowed_modules):
616
+ self.allowed_modules = allowed_modules
617
+
618
+ def __call__(self, name, *args, **kwargs):
619
+ if name in self.allowed_modules:
620
+ return __import__(name, *args, **kwargs)
621
+ else:
622
+ raise ImportError(f"Import of '{{name}}' is not allowed for security reasons. " +
623
+ f"Allowed modules: {{', '.join(sorted(self.allowed_modules))}}")
624
+
625
+ # Capture stdout and stderr
626
+ original_stdout = sys.stdout
627
+ original_stderr = sys.stderr
628
+ sys.stdout = LogCapture("log")
629
+ sys.stderr = LogCapture("error")
630
+
631
+ # Parse input data
632
+ try:
633
+ input_data = json.loads(r"""{input_data}""")
634
+ except json.JSONDecodeError as e:
635
+ original_stderr.write(json.dumps({{"error": f"Failed to parse input data: {{e}}"}}))
636
+ sys.exit(1)
637
+
638
+ # Create safe environment
639
+ safe_globals = {{
640
+ "__builtins__": {{
641
+ # Safe builtins only
642
+ "abs": abs, "all": all, "any": any, "bool": bool,
643
+ "chr": chr, "dict": dict, "divmod": divmod,
644
+ "enumerate": enumerate, "filter": filter, "float": float,
645
+ "format": format, "frozenset": frozenset, "hash": hash,
646
+ "hex": hex, "int": int, "isinstance": isinstance,
647
+ "issubclass": issubclass, "iter": iter, "len": len,
648
+ "list": list, "map": map, "max": max, "min": min,
649
+ "next": next, "oct": oct, "ord": ord, "pow": pow,
650
+ "print": print, "range": range, "repr": repr,
651
+ "reversed": reversed, "round": round, "set": set,
652
+ "slice": slice, "sorted": sorted, "str": str, "sum": sum,
653
+ "tuple": tuple, "type": type, "zip": zip,
654
+ # Exception types for error handling
655
+ "Exception": Exception, "ValueError": ValueError,
656
+ "TypeError": TypeError, "KeyError": KeyError,
657
+ "IndexError": IndexError,
658
+ # Add a safe import function
659
+ "__import__": RestrictedImporter({{
660
+ "json", "datetime", "math", "statistics", "collections",
661
+ "itertools", "functools", "re", "copy", "decimal",
662
+ "csv", "io", "dataclasses", "typing", "enum"
663
+ }})
664
+ }},
665
+ # Pre-import safe modules
666
+ "json": json,
667
+ "datetime": datetime,
668
+ "math": math,
669
+ "statistics": statistics,
670
+ "collections": collections,
671
+ "itertools": itertools,
672
+ "functools": functools,
673
+ "re": re
674
+ }}
675
+
676
+ safe_locals = {{"input_data": input_data}}
677
+
678
+ # Define transform function from user script in a safe context
679
+ try:
680
+ compiled_code = compile(r"""{user_script}""", "<user_script>", "exec")
681
+ exec(compiled_code, safe_globals, safe_locals)
682
+
683
+ # Validate transform function exists and has correct signature
684
+ if 'transform' not in safe_locals:
685
+ original_stderr.write(json.dumps({{"error": "No transform function defined"}}))
686
+ sys.exit(1)
687
+
688
+ if not callable(safe_locals['transform']):
689
+ original_stderr.write(json.dumps({{"error": "transform must be a function"}}))
690
+ sys.exit(1)
691
+
692
+ transform_fn = safe_locals['transform']
693
+
694
+ except Exception as e:
695
+ original_stderr.write(json.dumps({{
696
+ "error": str(e),
697
+ "stack": traceback.format_exc().split('\\n')
698
+ }}))
699
+ sys.exit(1)
700
+
701
+ # Execute transform with input data
702
+ try:
703
+ # Cancel the alarm if we reach here (we have our own timeout)
704
+ try:
705
+ signal.alarm(0)
706
+ except:
707
+ pass
708
+
709
+ result = transform_fn(input_data)
710
+
711
+ # Basic validation of output (to prevent non-serializable data)
712
+ try:
713
+ json.dumps(result)
714
+ except TypeError as e:
715
+ raise TypeError(f"Transform result is not JSON serializable: {{e}}")
716
+
717
+ # Write result to original stdout
718
+ original_stdout.write(json.dumps({{"result": result, "logs": logs}}))
719
+
720
+ except Exception as e:
721
+ original_stderr.write(json.dumps({{
722
+ "error": str(e),
723
+ "stack": traceback.format_exc().split('\\n')
724
+ }}))
725
+ sys.exit(1)
726
+ finally:
727
+ # Restore stdout and stderr
728
+ sys.stdout = original_stdout
729
+ sys.stderr = original_stderr
730
+ '''
731
+
732
+ def execute(self, program_file: str, input_data: str) -> Tuple[Union[Dict, str], Optional[str]]:
733
+ logger.info(f"Executing Python script: {program_file}")
734
+ stats = Stats()
735
+
736
+ try:
737
+ check_resource_limits(self.modules_dir)
738
+
739
+ with tempfile.TemporaryDirectory() as temp_dir:
740
+ temp_dir = Path(temp_dir)
741
+
742
+ # Read user script
743
+ with open(program_file, 'r') as f:
744
+ user_script = f.read()
745
+ logger.debug("Loaded user Python script: %d characters", len(user_script))
746
+
747
+ # Check for dangerous code
748
+ safety_issue = self.check_for_dangerous_code(user_script)
749
+ if safety_issue:
750
+ logger.warning(f"Security violation detected in script: {safety_issue}")
751
+ return {
752
+ "lam.error": f"Security violation: {safety_issue}",
753
+ "type": "SecurityError"
754
+ }, f"Security violation: {safety_issue}"
755
+
756
+ # Create wrapper script
757
+ wrapper = self.create_wrapper(input_data, user_script)
758
+ script_path = temp_dir / "script.py"
759
+ with open(script_path, 'w') as f:
760
+ f.write(wrapper)
761
+ logger.debug("Generated Python wrapper script: %s", script_path)
762
+
763
+ # Execute with Python in isolated environment
764
+ process = subprocess.Popen(
765
+ [
766
+ sys.executable,
767
+ "-I", # Isolated mode, ignores environment variables/site packages
768
+ str(script_path)
769
+ ],
770
+ stdout=subprocess.PIPE,
771
+ stderr=subprocess.PIPE,
772
+ text=True,
773
+ cwd=temp_dir,
774
+ # Prevent access to system environment variables
775
+ env={"PATH": os.environ.get("PATH", "")}
776
+ )
777
+ logger.info("Started Python process PID %d", process.pid)
778
+
779
+ try:
780
+ output, error = process.communicate(timeout=5)
781
+ logger.debug("Process completed with code %d", process.returncode)
782
+ except subprocess.TimeoutExpired as e:
783
+ logger.warning("Process timeout after 5 seconds")
784
+ process.kill()
785
+ return {"lam.error": "Script execution timed out"}, "Execution timed out after 5 seconds"
786
+
787
+ # Handle process errors
788
+ if process.returncode != 0:
789
+ try:
790
+ # Try to parse structured error from stderr
791
+ error_data = json.loads(error.strip())
792
+ error_msg = error_data.get('error', 'Unknown error')
793
+ stack = error_data.get('stack', [])
794
+
795
+ # Format error message
796
+ error_details = {
797
+ "lam.error": error_msg,
798
+ "stack_trace": stack
799
+ }
800
+ return error_details, error_msg
801
+
802
+ except json.JSONDecodeError:
803
+ # Fallback to raw error output
804
+ error_msg = error.strip() or "Unknown error"
805
+ return {"lam.error": error_msg}, error_msg
806
+
807
+ # Handle successful output
808
+ try:
809
+ output_data = json.loads(output)
810
+
811
+ # Process Python logs (if any)
812
+ if 'logs' in output_data:
813
+ for log_entry in output_data.get('logs', []):
814
+ if log_entry['type'] == 'error':
815
+ logger.error("[Python] %s", log_entry['message'])
816
+ else:
817
+ logger.debug("[Python] %s", log_entry['message'])
818
+
819
+ result = output_data.get('result', {})
820
+ return result, None
821
+
822
+ except json.JSONDecodeError as e:
823
+ logger.error("Failed to parse output: %s", str(e))
824
+ return {
825
+ "lam.error": "Invalid JSON output",
826
+ "raw_output": output.strip()
827
+ }, "Output format error"
828
+
829
+ except Exception as e:
830
+ logger.exception("Execution failed")
831
+ return {
832
+ "lam.error": str(e),
833
+ "type": e.__class__.__name__
834
+ }, str(e)
835
+
444
836
  def get_engine(engine_type: str, workspace_id: str, flow_id: str, execution_id: str) -> Engine:
445
837
  """Factory function to get the appropriate execution engine"""
446
838
  engines = {
447
839
  EngineType.JQ.value: JQEngine,
448
- EngineType.JAVASCRIPT.value: BunEngine
840
+ EngineType.JAVASCRIPT.value: BunEngine,
841
+ EngineType.PYTHON.value: PythonEngine
449
842
  }
450
843
 
451
844
  engine_class = engines.get(engine_type)
@@ -481,7 +874,7 @@ def lam():
481
874
  @lam.command()
482
875
  @click.argument('program_file', type=click.Path(exists=True))
483
876
  @click.argument('input', type=str)
484
- @click.option('--language', type=click.Choice(['jq', 'js']), default='jq',
877
+ @click.option('--language', type=click.Choice(['jq', 'js', 'py']), default='jq',
485
878
  help='Script language (default: jq)')
486
879
  @click.option('--workspace_id', default="local", help="Workspace ID")
487
880
  @click.option('--flow_id', default="local", help="Flow ID")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lam-cli
3
- Version: 0.1.4
3
+ Version: 0.1.5
4
4
  Summary: Secure data transformation tool supporting JQ and JavaScript (Bun)
5
5
  Home-page: https://github.com/laminar-run/lam
6
6
  Author: Laminar Run, Inc.
@@ -8,7 +8,7 @@ long_description = docs_path.read_text() if docs_path.exists() else ""
8
8
 
9
9
  setup(
10
10
  name="lam-cli",
11
- version="0.1.4",
11
+ version="0.1.5",
12
12
  packages=find_packages(),
13
13
  install_requires=[
14
14
  "backoff>=2.2.1",
File without changes
File without changes
File without changes
File without changes