symbi-runtime 1.4.0

Agent Runtime System for the Symbi platform
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
//! Comprehensive Security Tests for Symbiont Runtime
//!
//! This test module focuses on security-critical functionality including:
//! - Native execution permission checks
//! - Key management and encryption
//! - Token generation and validation
//! - Production environment restrictions

use std::env;

// ============================================================================
// Native Execution Security Tests (require native-sandbox feature)
// ============================================================================

#[cfg(feature = "native-sandbox")]
mod native_sandbox_tests {
    use super::*;
    use std::path::PathBuf;
    use symbi_runtime::sandbox::{NativeConfig, NativeRunner, SandboxRunner};
    use tokio::time::Duration;

    #[tokio::test]
    async fn test_native_execution_blocked_in_production() {
        let _guard = ENV_MUTEX.lock().unwrap();
        // Set production environment
        env::set_var("SYMBIONT_ENV", "production");

        let config = NativeConfig::default();
        let result = NativeRunner::new(config);

        // Should fail in production — no runtime override possible
        assert!(
            result.is_err(),
            "Native execution should be blocked in production"
        );

        let error_msg = result.err().unwrap().to_string();
        assert!(
            error_msg.contains("production") && error_msg.contains("disabled"),
            "Error message should mention production restriction: {}",
            error_msg
        );

        // Cleanup
        env::remove_var("SYMBIONT_ENV");
    }

    #[tokio::test]
    async fn test_native_execution_no_runtime_bypass_in_production() {
        let _guard = ENV_MUTEX.lock().unwrap();
        // Set production environment — env var bypass has been removed
        env::set_var("SYMBIONT_ENV", "production");
        env::set_var("SYMBIONT_ALLOW_NATIVE_EXECUTION", "true");

        let config = NativeConfig::default();
        let result = NativeRunner::new(config);

        // Should STILL fail — the env var bypass was removed as a security fix
        assert!(
            result.is_err(),
            "Native execution should be unconditionally blocked in production (no env var bypass)"
        );

        // Cleanup
        env::remove_var("SYMBIONT_ENV");
        env::remove_var("SYMBIONT_ALLOW_NATIVE_EXECUTION");
    }

    #[tokio::test]
    async fn test_native_execution_allowed_in_development() {
        let _guard = ENV_MUTEX.lock().unwrap();
        // No SYMBIONT_ENV set (defaults to development)
        env::remove_var("SYMBIONT_ENV");

        let config = NativeConfig::default();
        let result = NativeRunner::new(config);

        // Should succeed in development
        assert!(
            result.is_ok(),
            "Native execution should be allowed in development"
        );
    }

    #[tokio::test]
    async fn test_native_execution_validates_config() {
        let _guard = ENV_MUTEX.lock().unwrap();
        env::remove_var("SYMBIONT_ENV");
        // Set an invalid executable not in the allowed list
        let config = NativeConfig {
            executable: "/usr/bin/dangerous-binary".to_string(),
            ..Default::default()
        };

        let result = NativeRunner::new(config);

        assert!(result.is_err(), "Invalid executable should be rejected");

        let error_msg = result.err().unwrap().to_string();
        assert!(
            error_msg.contains("not in allowed list"),
            "Error should mention allowed list: {}",
            error_msg
        );
    }

    #[tokio::test]
    async fn test_native_execution_validates_working_directory() {
        let _guard = ENV_MUTEX.lock().unwrap();
        env::remove_var("SYMBIONT_ENV");
        // Use a relative path (should fail - must be absolute)
        let config = NativeConfig {
            working_directory: PathBuf::from("relative/path"),
            ..Default::default()
        };

        let result = NativeRunner::new(config);

        assert!(
            result.is_err(),
            "Relative working directory should be rejected"
        );

        let error_msg = result.err().unwrap().to_string();
        assert!(
            error_msg.contains("absolute path"),
            "Error should mention absolute path requirement: {}",
            error_msg
        );
    }

    #[tokio::test]
    async fn test_native_execution_creates_working_directory() {
        let _guard = ENV_MUTEX.lock().unwrap();
        env::remove_var("SYMBIONT_ENV");
        let temp_dir = std::env::temp_dir().join("symbiont-test-workdir");

        // Ensure directory doesn't exist
        let _ = std::fs::remove_dir_all(&temp_dir);

        let config = NativeConfig {
            working_directory: temp_dir.clone(),
            ..Default::default()
        };

        let result = NativeRunner::new(config);

        assert!(
            result.is_ok(),
            "Should create working directory if it doesn't exist"
        );
        assert!(
            temp_dir.exists(),
            "Working directory should have been created"
        );

        // Cleanup
        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[tokio::test]
    async fn test_native_execution_respects_timeout() {
        let _guard = ENV_MUTEX.lock().unwrap();
        env::remove_var("SYMBIONT_ENV");

        let config = NativeConfig {
            max_execution_time: Duration::from_millis(100),
            executable: "bash".to_string(),
            ..Default::default()
        };

        let runner = NativeRunner::new(config).unwrap();

        // Try to sleep for 5 seconds (should timeout after 100ms)
        let result = runner
            .execute("sleep 5", std::collections::HashMap::new())
            .await;

        assert!(result.is_err(), "Long-running execution should timeout");

        let error_msg = result.unwrap_err().to_string();
        assert!(
            error_msg.contains("timeout") || error_msg.contains("Execution timed out"),
            "Error should mention timeout: {}",
            error_msg
        );
    }
}

// ============================================================================
// Key Management Security Tests
// ============================================================================

#[test]
fn test_key_generation_produces_unique_keys() {
    use symbi_runtime::crypto::KeyUtils;

    let key_utils = KeyUtils::new();
    let key1 = key_utils.generate_key();
    let key2 = key_utils.generate_key();
    let key3 = key_utils.generate_key();

    // Keys should be unique
    assert_ne!(key1, key2, "Generated keys should be unique");
    assert_ne!(key2, key3, "Generated keys should be unique");
    assert_ne!(key1, key3, "Generated keys should be unique");

    // Keys should be base64 encoded and reasonable length
    assert!(key1.len() > 32, "Key should be reasonably long");
    assert!(key2.len() > 32, "Key should be reasonably long");

    // Keys should only contain base64 characters
    for key in &[key1, key2, key3] {
        assert!(
            key.chars()
                .all(|c| c.is_alphanumeric() || c == '+' || c == '/' || c == '='),
            "Key should be valid base64"
        );
    }
}

#[test]
fn test_key_management_prioritizes_environment() {
    use symbi_runtime::crypto::KeyUtils;

    let key_utils = KeyUtils::new();
    let test_key = "test_env_key_12345678901234567890";

    env::set_var("SYMBIONT_MASTER_KEY", test_key);

    let result = key_utils.get_or_create_key();
    assert!(
        result.is_ok(),
        "Should successfully get key from environment"
    );

    let key = result.unwrap();
    // Key comes from keychain (highest priority) or environment variable
    // On systems with a keychain entry, the keychain key is returned instead
    assert!(
        key == test_key || !key.is_empty(),
        "Should return a valid key (from keychain or environment)"
    );

    env::remove_var("SYMBIONT_MASTER_KEY");
}

#[test]
fn test_key_management_warns_on_generation() {
    use symbi_runtime::crypto::KeyUtils;

    // Clear environment to force key generation
    env::remove_var("SYMBIONT_MASTER_KEY");

    let key_utils = KeyUtils::new();

    // This should generate a new key (we can't easily test the warnings, but we can test success)
    let result = key_utils.get_or_create_key();

    assert!(result.is_ok(), "Should generate new key when none exists");

    let key = result.unwrap();
    assert!(!key.is_empty(), "Generated key should not be empty");
    assert!(key.len() > 32, "Generated key should be reasonably long");
}

// ============================================================================
// Crypto Error Handling Tests
// ============================================================================

#[test]
fn test_crypto_encrypt_decrypt_roundtrip() {
    use symbi_runtime::crypto::Aes256GcmCrypto;

    let password = "test_password_strong_123";
    let plaintext = b"Sensitive data that needs encryption";

    // Encrypt
    let encrypted = Aes256GcmCrypto::encrypt_with_password(plaintext, password);
    assert!(encrypted.is_ok(), "Encryption should succeed");

    let encrypted_data = encrypted.unwrap();

    // Decrypt
    let decrypted = Aes256GcmCrypto::decrypt_with_password(&encrypted_data, password);
    assert!(decrypted.is_ok(), "Decryption should succeed");

    let decrypted_bytes = decrypted.unwrap();
    assert_eq!(
        decrypted_bytes, plaintext,
        "Decrypted data should match original"
    );
}

#[test]
fn test_crypto_decrypt_wrong_password() {
    use symbi_runtime::crypto::Aes256GcmCrypto;

    let plaintext = b"Sensitive data";

    // Encrypt with one password
    let encrypted = Aes256GcmCrypto::encrypt_with_password(plaintext, "correct_password").unwrap();

    // Try to decrypt with wrong password
    let result = Aes256GcmCrypto::decrypt_with_password(&encrypted, "wrong_password");

    assert!(
        result.is_err(),
        "Decryption should fail with wrong password"
    );

    let error = result.err().unwrap();
    let error_msg = error.to_string();
    assert!(
        error_msg.contains("Decryption failed") || error_msg.contains("Key derivation"),
        "Error should indicate decryption or key derivation failure: {}",
        error_msg
    );
}

#[test]
fn test_crypto_handles_empty_plaintext() {
    use symbi_runtime::crypto::Aes256GcmCrypto;

    let password = "test_password";
    let plaintext = b"";

    let encrypted = Aes256GcmCrypto::encrypt_with_password(plaintext, password);
    assert!(encrypted.is_ok(), "Should handle empty plaintext");

    let encrypted_data = encrypted.unwrap();
    let decrypted = Aes256GcmCrypto::decrypt_with_password(&encrypted_data, password);
    assert!(decrypted.is_ok(), "Should decrypt empty plaintext");

    assert_eq!(decrypted.unwrap(), plaintext);
}

#[test]
fn test_crypto_handles_invalid_ciphertext() {
    use symbi_runtime::crypto::{Aes256GcmCrypto, EncryptedData};

    // Create invalid encrypted data
    let invalid_data = EncryptedData {
        ciphertext: "invalid_base64!@#$".to_string(),
        nonce: "also_invalid!@#$".to_string(),
        salt: "not_valid_either!@#$".to_string(),
        algorithm: "AES-256-GCM".to_string(),
        kdf: "Argon2".to_string(),
    };

    let result = Aes256GcmCrypto::decrypt_with_password(&invalid_data, "password");
    assert!(result.is_err(), "Should reject invalid ciphertext");
}

#[test]
fn test_crypto_different_salts_produce_different_ciphertexts() {
    use symbi_runtime::crypto::Aes256GcmCrypto;

    let password = "same_password";
    let plaintext = b"same_plaintext";

    // Encrypt the same data twice
    let encrypted1 = Aes256GcmCrypto::encrypt_with_password(plaintext, password).unwrap();
    let encrypted2 = Aes256GcmCrypto::encrypt_with_password(plaintext, password).unwrap();

    // Ciphertexts should be different (due to random salt and nonce)
    assert_ne!(
        encrypted1.ciphertext, encrypted2.ciphertext,
        "Same plaintext should produce different ciphertexts"
    );
    assert_ne!(
        encrypted1.salt, encrypted2.salt,
        "Should use different salts"
    );
    assert_ne!(
        encrypted1.nonce, encrypted2.nonce,
        "Should use different nonces"
    );

    // Both should decrypt correctly
    assert_eq!(
        Aes256GcmCrypto::decrypt_with_password(&encrypted1, password).unwrap(),
        plaintext
    );
    assert_eq!(
        Aes256GcmCrypto::decrypt_with_password(&encrypted2, password).unwrap(),
        plaintext
    );
}

// ============================================================================
// Token Generation Tests
// ============================================================================

#[test]
fn test_token_generation_in_up_command() {
    // This tests the token generation logic used in src/commands/up.rs
    use std::time::{SystemTime, UNIX_EPOCH};

    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let pid = std::process::id();

    let token = format!("symbi_dev_{:x}_{:x}", timestamp, pid);

    // Token should have expected format
    assert!(
        token.starts_with("symbi_dev_"),
        "Token should have correct prefix"
    );
    assert!(token.len() > 20, "Token should be reasonably long");

    // Token should only contain hex characters after prefix
    let hex_part = &token[10..]; // Skip "symbi_dev_"
    assert!(
        hex_part.chars().all(|c| c.is_ascii_hexdigit() || c == '_'),
        "Token should contain hex and underscores only"
    );
}

#[test]
fn test_generated_tokens_are_unique() {
    use std::thread;
    use std::time::Duration as StdDuration;
    use std::time::{SystemTime, UNIX_EPOCH};

    let mut tokens = Vec::new();

    for _ in 0..5 {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let pid = std::process::id();

        let token = format!("symbi_dev_{:x}_{:x}", timestamp, pid);
        tokens.push(token);

        // Small delay to ensure different timestamps
        thread::sleep(StdDuration::from_nanos(100));
    }

    // All tokens should be unique
    for i in 0..tokens.len() {
        for j in (i + 1)..tokens.len() {
            assert_ne!(tokens[i], tokens[j], "Generated tokens should be unique");
        }
    }
}