about summary refs log tree commit diff stats
path: root/bash/talk-to-computer/lil_tester.sh
blob: 8bdcc41707ac18281895d6031bd82e6c1c830685 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#!/bin/bash

# Lil Script Tester - Secure Sandbox Testing Module
# This module provides secure testing capabilities for Lil scripts generated by the puzzle mechanism.
#
# SECURITY FEATURES:
# - Sandboxed execution environment
# - Resource limits (CPU, memory, time)
# - File system isolation
# - Network access prevention
# - Safe error handling
# - Result validation and sanitization

# --- Configuration ---
TEST_TIMEOUT=10          # Maximum execution time in seconds
MAX_OUTPUT_SIZE=10000    # Maximum output size in characters
TEMP_DIR_BASE="/tmp/lil_test"  # Base temporary directory
SAFE_COMMANDS=("print" "echo" "count" "first" "last" "sum" "min" "max" "range" "keys" "list" "table" "typeof" "mag" "unit")

# --- Security Functions ---

# Create secure temporary directory
create_secure_temp_dir() {
    local dir="$1"
    mkdir -p "$dir"
    chmod 700 "$dir"
    
    # Create a minimal environment
    echo "()" > "$dir/empty.lil"
    echo "nil" > "$dir/nil.lil"
}

# Clean up temporary directory
cleanup_temp_dir() {
    local dir="$1"
    if [ -d "$dir" ]; then
        rm -rf "$dir" 2>/dev/null
    fi
}

# Validate Lil code for potentially dangerous operations
validate_lil_code() {
    local code="$1"
    
    # Check for potentially dangerous patterns
    local dangerous_patterns=(
        "system\\["           # System calls
        "exec\\["             # Execution
        "file\\."             # File operations
        "network\\."          # Network operations
        "http\\."             # HTTP requests
        "shell\\["            # Shell execution
        "\\$\\("              # Command substitution
        "\\`.*\\`"            # Backtick execution
    )
    
    for pattern in "${dangerous_patterns[@]}"; do
        if echo "$code" | grep -q "$pattern" 2>/dev/null; then
            echo "DANGEROUS_CODE_DETECTED: $pattern"
            return 1
        fi
    done
    
    # Check for reasonable complexity (prevent infinite loops)
    local line_count=$(echo "$code" | wc -l)
    if [ "$line_count" -gt 100 ]; then
        echo "CODE_TOO_COMPLEX: $line_count lines (max: 100)"
        return 1
    fi
    
    echo "CODE_VALIDATED"
    return 0
}

# Create a safe test wrapper
create_safe_test_wrapper() {
    local code="$1"
    local test_name="$2"
    local temp_dir="$3"
    
    # Create a safe test file
    cat > "$temp_dir/test_$test_name.lil" << EOF
# Safe test wrapper for: $test_name
# Generated by Lil Tester

# Set safe defaults
on safe_test do
    local result
    local error_occurred
    
    # Wrap execution in error handling
    on execute_safely do
        $code
    end
    
    # Execute and capture result
    result:execute_safely()
    
    # Return result or error indicator
    if result = nil
        "ERROR: Execution failed or returned nil"
    else
        result
    end
end

# Run the test
safe_test()
EOF
}

# Execute Lil code safely
execute_lil_safely() {
    local code="$1"
    local test_name="$2"
    local temp_dir="$3"
    
    # Validate code first
    local validation_result=$(validate_lil_code "$code")
    if [ $? -ne 0 ]; then
        echo "VALIDATION_FAILED: $validation_result"
        return 1
    fi
    
    # Create safe test wrapper
    create_safe_test_wrapper "$code" "$test_name" "$temp_dir"
    
    # Try lilt first, fallback to lila
    local result=""
    local exit_code=1
    
    # Test with lilt
    if command -v lilt >/dev/null 2>&1; then
        echo "Testing with lilt..."
        result=$(timeout "$TEST_TIMEOUT" lilt "$temp_dir/test_$test_name.lil" 2>&1)
        exit_code=$?
        
        if [ $exit_code -eq 0 ]; then
            echo "SUCCESS: lilt execution completed"
        else
            echo "lilt failed, trying lila..."
        fi
    fi
    
    # Fallback to lila if lilt failed
    if [ $exit_code -ne 0 ] && command -v lila >/dev/null 2>&1; then
        echo "Testing with lila..."
        result=$(timeout "$TEST_TIMEOUT" lila "$temp_dir/test_$test_name.lil" 2>&1)
        exit_code=$?
        
        if [ $exit_code -eq 0 ]; then
            echo "SUCCESS: lila execution completed"
        else
            echo "Both lilt and lila failed"
        fi
    fi
    
    # Check output size
    local output_size=${#result}
    if [ "$output_size" -gt "$MAX_OUTPUT_SIZE" ]; then
        result="$(echo "$result" | head -c "$MAX_OUTPUT_SIZE")... [TRUNCATED]"
    fi
    
    echo "$result"
    return $exit_code
}

# Run comprehensive tests
run_lil_tests() {
    local code="$1"
    local test_name="$2"
    
    # Create unique temporary directory
    local temp_dir="${TEMP_DIR_BASE}_$$_$(date +%s)"
    
    echo "=== Lil Script Testing ==="
    echo "Test Name: $test_name"
    echo "Code Length: $(echo "$code" | wc -c) characters"
    echo "----------------------------------------"
    
    # Create secure temporary directory
    create_secure_temp_dir "$temp_dir"
    
    # Trap cleanup on exit
    trap 'cleanup_temp_dir "$temp_dir"' EXIT
    
    # Execute the code safely
    local start_time=$(date +%s.%N)
    local result=$(execute_lil_safely "$code" "$test_name" "$temp_dir")
    local exit_code=$?
    local end_time=$(date +%s.%N)
    
    # Calculate execution time
    local duration=$(echo "$end_time - $start_time" | bc -l 2>/dev/null || echo "0")
    
    # Report results
    echo "----------------------------------------"
    echo "Test Results:"
    echo "Exit Code: $exit_code"
    echo "Execution Time: ${duration}s"
    echo "Output:"
    echo "$result"
    
    if [ $exit_code -eq 0 ]; then
        echo "✅ Test PASSED"
        return 0
    else
        echo "❌ Test FAILED"
        return 1
    fi
}

# Test specific Lil constructs
test_lil_constructs() {
    local code="$1"
    local test_name="$2"
    
    # Create unique temporary directory for construct testing
    local temp_dir="${TEMP_DIR_BASE}_constructs_$$_$(date +%s)"
    
    echo "=== Lil Construct Testing ==="
    echo "Testing specific Lil language features..."
    
    # Create and cleanup temp dir
    create_secure_temp_dir "$temp_dir"
    trap 'cleanup_temp_dir "$temp_dir"' EXIT
    
    # Test basic operations
    local basic_tests=(
        "Basic arithmetic: 2+3*4"
        "List operations: (1,2,3) take 2"
        "Dictionary: dict (\"a\",1) (\"b\",2)"
        "Function definition: on test do 42 end"
    )
    
    for test in "${basic_tests[@]}"; do
        local test_desc=$(echo "$test" | cut -d: -f1)
        local test_code=$(echo "$test" | cut -d: -f2)
        
        echo "Testing: $test_desc"
        local result=$(execute_lil_safely "$test_code" "basic_$test_desc" "$temp_dir")
        
        if [ $? -eq 0 ]; then
            echo "  ✅ $test_desc: PASSED"
        else
            echo "  ❌ $test_desc: FAILED"
        fi
    done
}

# Main testing interface
test_lil_script() {
    local code="$1"
    local test_name="${2:-unnamed_test}"
    
    if [ -z "$code" ]; then
        echo "Error: No code provided for testing"
        return 1
    fi
    
    # Run the main test
    run_lil_tests "$code" "$test_name"
    local main_result=$?
    
    # Run construct-specific tests
    test_lil_constructs "$code" "$test_name"
    
    return $main_result
}

# Export functions for use by other scripts
export -f test_lil_script
export -f run_lil_tests
export -f execute_lil_safely
export -f validate_lil_code
export -f create_secure_temp_dir
export -f cleanup_temp_dir

# If run directly, provide usage information
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    if [ "$#" -lt 1 ]; then
        echo "Usage: $0 <lil_code> [test_name]"
        echo "Example: $0 'on test do 42 end' 'simple_function'"
        exit 1
    fi
    
    test_lil_script "$1" "${2:-unnamed_test}"
fi