nika 0.35.4

Semantic YAML workflow engine for AI tasks - DAG execution, MCP integration, multi-provider LLM support
Documentation
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Comprehensive exec verb error path tests (v0.21.3)
//!
//! Tests all error conditions in the exec verb implementation:
//! - Empty command
//! - Shlex parse failures (unbalanced quotes)
//! - Command not found (nonexistent binary)
//! - Non-zero exit codes with various exit statuses
//! - Stderr output capture
//! - Template resolution failures
//! - Security blocklist violations
//! - Policy violations
//! - Working directory (cwd) errors

use nika::ast::{ExecParams, TaskAction};
use nika::binding::ResolvedBindings;
use nika::error::NikaError;
use nika::event::EventLog;
use nika::runtime::TaskExecutor;
use nika::store::RunContext;
use std::sync::Arc;

/// Helper to create executor with default settings
fn create_executor() -> TaskExecutor {
    TaskExecutor::new("mock", None, None, EventLog::new())
}

/// Helper to execute an exec action
async fn run_exec(
    executor: &TaskExecutor,
    task_id: &str,
    command: &str,
    shell: Option<bool>,
) -> Result<String, NikaError> {
    let action = TaskAction::Exec {
        exec: ExecParams {
            command: command.to_string(),
            shell,
            timeout: None,
            cwd: None,
            env: None,
        },
    };
    let task_id: Arc<str> = Arc::from(task_id);
    let bindings = ResolvedBindings::new();
    let datastore = RunContext::new();

    executor
        .execute(&task_id, &action, &bindings, &datastore, None)
        .await
}

// ============================================================================
// EMPTY COMMAND TESTS
// ============================================================================

#[tokio::test]
async fn test_exec_empty_command_string() {
    let executor = create_executor();
    let result = run_exec(&executor, "empty_cmd", "", None).await;

    assert!(result.is_err());
    let err = result.unwrap_err();
    // Empty command should fail during shlex parsing or validation
    assert!(
        matches!(err, NikaError::Execution(_)),
        "Expected Execution error, got: {err:?}"
    );
}

#[tokio::test]
async fn test_exec_whitespace_only_command() {
    let executor = create_executor();
    let result = run_exec(&executor, "whitespace_cmd", "   ", None).await;

    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        matches!(err, NikaError::Execution(_)),
        "Expected Execution error, got: {err:?}"
    );
}

// ============================================================================
// SHLEX PARSE ERROR TESTS
// ============================================================================

#[tokio::test]
async fn test_exec_unbalanced_single_quotes() {
    let executor = create_executor();
    // Missing closing single quote
    let result = run_exec(&executor, "unbalanced_single", "echo 'hello", None).await;

    assert!(result.is_err());
    let err = result.unwrap_err();
    if let NikaError::Execution(msg) = &err {
        assert!(
            msg.contains("unbalanced") || msg.contains("parse") || msg.contains("quote"),
            "Expected parse error message, got: {msg}"
        );
    } else {
        panic!("Expected Execution error, got: {err:?}");
    }
}

#[tokio::test]
async fn test_exec_unbalanced_double_quotes() {
    let executor = create_executor();
    // Missing closing double quote
    let result = run_exec(&executor, "unbalanced_double", "echo \"hello", None).await;

    assert!(result.is_err());
    let err = result.unwrap_err();
    if let NikaError::Execution(msg) = &err {
        assert!(
            msg.contains("unbalanced") || msg.contains("parse") || msg.contains("quote"),
            "Expected parse error message, got: {msg}"
        );
    } else {
        panic!("Expected Execution error, got: {err:?}");
    }
}

#[tokio::test]
async fn test_exec_mixed_unbalanced_quotes() {
    let executor = create_executor();
    // Mixed unbalanced quotes
    let result = run_exec(&executor, "mixed_quotes", "echo \"hello'", None).await;

    assert!(result.is_err());
}

// ============================================================================
// COMMAND NOT FOUND TESTS
// ============================================================================

#[tokio::test]
async fn test_exec_nonexistent_command() {
    let executor = create_executor();
    // Command that definitely doesn't exist
    let result = run_exec(
        &executor,
        "nonexistent",
        "this_command_definitely_does_not_exist_12345",
        None,
    )
    .await;

    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        matches!(err, NikaError::Execution(_)),
        "Expected Execution error, got: {err:?}"
    );
}

#[tokio::test]
async fn test_exec_nonexistent_command_shell_mode() {
    let executor = create_executor();
    // Nonexistent command in shell mode
    let result = run_exec(
        &executor,
        "nonexistent_shell",
        "this_command_definitely_does_not_exist_12345",
        Some(true),
    )
    .await;

    assert!(result.is_err());
}

// ============================================================================
// EXIT CODE TESTS
// ============================================================================

#[tokio::test]
async fn test_exec_exit_code_1() {
    let executor = create_executor();
    // false command always returns exit code 1
    let result = run_exec(&executor, "exit_1", "false", None).await;

    assert!(result.is_err());
    let err = result.unwrap_err();
    if let NikaError::Execution(msg) = &err {
        assert!(
            msg.contains("failed") || msg.contains("Command"),
            "Expected failure message, got: {msg}"
        );
    } else {
        panic!("Expected Execution error, got: {err:?}");
    }
}

#[tokio::test]
async fn test_exec_exit_code_1_shell_mode() {
    let executor = create_executor();
    // exit 1 in shell mode
    let result = run_exec(&executor, "exit_1_shell", "exit 1", Some(true)).await;

    assert!(result.is_err());
}

#[tokio::test]
async fn test_exec_exit_code_2() {
    let executor = create_executor();
    // Shell exit 2 (often indicates invalid usage)
    let result = run_exec(&executor, "exit_2", "exit 2", Some(true)).await;

    assert!(result.is_err());
}

#[tokio::test]
async fn test_exec_exit_code_127() {
    let executor = create_executor();
    // exit 127 is "command not found" in shell
    let result = run_exec(&executor, "exit_127", "exit 127", Some(true)).await;

    assert!(result.is_err());
}

// ============================================================================
// STDERR OUTPUT TESTS
// ============================================================================

#[tokio::test]
async fn test_exec_stderr_output_captured() {
    let executor = create_executor();
    // Command that writes to stderr and exits with error
    let result = run_exec(
        &executor,
        "stderr_test",
        "echo 'error message' >&2 && false",
        Some(true),
    )
    .await;

    assert!(result.is_err());
    let err = result.unwrap_err();
    if let NikaError::Execution(msg) = &err {
        // Stderr should be captured in the error message
        assert!(
            msg.contains("error message") || msg.contains("failed"),
            "Expected stderr capture, got: {msg}"
        );
    }
}

#[tokio::test]
async fn test_exec_large_stderr() {
    let executor = create_executor();
    // Generate large stderr output
    let result = run_exec(
        &executor,
        "large_stderr",
        "for i in $(seq 1 100); do echo 'error line' >&2; done; false",
        Some(true),
    )
    .await;

    assert!(result.is_err());
}

// ============================================================================
// SECURITY BLOCKLIST TESTS (validates NIKA-053)
// ============================================================================

#[tokio::test]
async fn test_exec_blocked_rm_rf() {
    let executor = create_executor();
    let result = run_exec(&executor, "blocked_rm", "rm -rf /", None).await;

    assert!(result.is_err());
    let err = result.unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("NIKA-053") || msg.contains("blocked") || msg.contains("dangerous"),
        "Expected blocked command error, got: {msg}"
    );
}

#[tokio::test]
async fn test_exec_blocked_sudo() {
    let executor = create_executor();
    let result = run_exec(&executor, "blocked_sudo", "sudo ls", None).await;

    assert!(result.is_err());
}

#[tokio::test]
async fn test_exec_blocked_chmod_777() {
    let executor = create_executor();
    let result = run_exec(&executor, "blocked_chmod", "chmod 777 /", None).await;

    assert!(result.is_err());
}

#[tokio::test]
async fn test_exec_blocked_mkfs() {
    let executor = create_executor();
    let result = run_exec(&executor, "blocked_mkfs", "mkfs.ext4 /dev/sda", None).await;

    assert!(result.is_err());
}

#[tokio::test]
async fn test_exec_blocked_dd() {
    let executor = create_executor();
    let result = run_exec(&executor, "blocked_dd", "dd if=/dev/zero of=/dev/sda", None).await;

    assert!(result.is_err());
}

// ============================================================================
// TEMPLATE RESOLUTION ERROR TESTS
// ============================================================================

#[tokio::test]
async fn test_exec_template_missing_binding() {
    let executor = create_executor();
    let action = TaskAction::Exec {
        exec: ExecParams {
            command: "echo {{with.nonexistent}}".to_string(),
            shell: None,
            timeout: None,
            cwd: None,
            env: None,
        },
    };
    let task_id: Arc<str> = Arc::from("template_missing");
    let bindings = ResolvedBindings::new(); // Empty bindings
    let datastore = RunContext::new();

    let result = executor
        .execute(&task_id, &action, &bindings, &datastore, None)
        .await;

    assert!(result.is_err());
    let err = result.unwrap_err();
    // Should error on missing binding
    assert!(
        matches!(
            err,
            NikaError::TemplateError { .. } | NikaError::Execution(_)
        ),
        "Expected binding/template error, got: {err:?}"
    );
}

// ============================================================================
// SHELL MODE SPECIFIC TESTS
// ============================================================================

#[tokio::test]
async fn test_exec_shell_mode_pipes_work() {
    let executor = create_executor();
    // Pipe should work in shell mode
    let result = run_exec(
        &executor,
        "shell_pipe",
        "echo hello | tr a-z A-Z",
        Some(true),
    )
    .await;

    assert!(result.is_ok());
    let output = result.unwrap();
    assert!(output.contains("HELLO"), "Expected HELLO, got: {output}");
}

#[tokio::test]
async fn test_exec_shell_mode_redirects_work() {
    let executor = create_executor();
    // Redirect should work in shell mode
    let result = run_exec(
        &executor,
        "shell_redirect",
        "echo hello > /dev/null && echo done",
        Some(true),
    )
    .await;

    assert!(result.is_ok());
}

#[tokio::test]
async fn test_exec_shell_mode_command_chaining() {
    let executor = create_executor();
    // && should work in shell mode
    let result = run_exec(
        &executor,
        "shell_chain",
        "echo first && echo second",
        Some(true),
    )
    .await;

    assert!(result.is_ok());
    let output = result.unwrap();
    assert!(output.contains("first"));
    assert!(output.contains("second"));
}

#[tokio::test]
async fn test_exec_shell_false_prevents_chaining() {
    let executor = create_executor();
    // In shell-free mode, && is treated literally
    let result = run_exec(
        &executor,
        "no_chain",
        "echo hello && echo world",
        Some(false),
    )
    .await;

    // Should either succeed with literal output or fail (echo doesn't understand &&)
    // The key is that "world" shouldn't execute as a separate command
    if let Ok(output) = &result {
        // If it succeeds, the output should contain "&&" literally
        // or just the first word depending on how echo handles it
        assert!(
            !output.contains("world") || output.contains("&&"),
            "Shell chaining should not work: {output}"
        );
    }
}

// ============================================================================
// SUCCESS CASES (sanity checks)
// ============================================================================

#[tokio::test]
async fn test_exec_simple_echo_success() {
    let executor = create_executor();
    let result = run_exec(&executor, "echo_success", "echo hello", None).await;

    assert!(result.is_ok());
    let output = result.unwrap();
    assert!(output.contains("hello"));
}

#[tokio::test]
async fn test_exec_with_arguments() {
    let executor = create_executor();
    let result = run_exec(&executor, "with_args", "echo -n test", None).await;

    assert!(result.is_ok());
    let output = result.unwrap();
    assert!(output.contains("test"));
}

#[tokio::test]
async fn test_exec_with_spaces_in_quotes() {
    let executor = create_executor();
    let result = run_exec(&executor, "quoted_spaces", "echo 'hello world'", None).await;

    assert!(result.is_ok());
    let output = result.unwrap();
    assert!(output.contains("hello world"));
}