symbi-runtime 1.5.0

Agent Runtime System for the Symbi platform
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Configuration structures for secrets backends
//!
//! This module defines the configuration structures that can be deserialized
//! from symbiont.toml for different secrets backend types.

use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::time::Duration;

/// Configuration for secrets management
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecretsConfig {
    /// The secrets backend configuration
    #[serde(flatten)]
    pub backend: SecretsBackend,
    /// Common configuration options
    #[serde(default)]
    pub common: CommonSecretsConfig,
}

/// Enumeration of supported secrets backends
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum SecretsBackend {
    /// HashiCorp Vault backend
    Vault(VaultConfig),
    /// File-based secrets backend
    File(FileConfig),
}

/// Common configuration options for all secrets backends
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommonSecretsConfig {
    /// Timeout for secrets operations (in seconds)
    #[serde(default = "default_timeout")]
    pub timeout_seconds: u64,
    /// Maximum number of retry attempts
    #[serde(default = "default_max_retries")]
    pub max_retries: u32,
    /// Enable caching of secrets
    #[serde(default = "default_enable_cache")]
    pub enable_cache: bool,
    /// Cache TTL in seconds
    #[serde(default = "default_cache_ttl")]
    pub cache_ttl_seconds: u64,
    /// Audit configuration for secret operations
    pub audit: Option<super::auditing::AuditConfig>,
}

impl Default for CommonSecretsConfig {
    fn default() -> Self {
        Self {
            timeout_seconds: default_timeout(),
            max_retries: default_max_retries(),
            enable_cache: default_enable_cache(),
            cache_ttl_seconds: default_cache_ttl(),
            audit: None,
        }
    }
}

/// Configuration for HashiCorp Vault backend
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VaultConfig {
    /// Vault server URL
    pub url: String,
    /// Authentication method configuration
    pub auth: VaultAuthConfig,
    /// Vault namespace (optional)
    pub namespace: Option<String>,
    /// Default mount path for KV secrets engine
    #[serde(default = "default_vault_mount")]
    pub mount_path: String,
    /// API version for KV secrets engine (v1 or v2)
    #[serde(default = "default_vault_api_version")]
    pub api_version: String,
    /// TLS configuration
    #[serde(default)]
    pub tls: VaultTlsConfig,
    /// Connection pool settings
    #[serde(default)]
    pub connection: VaultConnectionConfig,
}

/// Vault authentication configuration
#[derive(Clone, Serialize, Deserialize)]
#[serde(tag = "method", rename_all = "lowercase")]
pub enum VaultAuthConfig {
    /// Token-based authentication
    Token {
        /// Vault token (can be from environment variable)
        token: String,
    },
    /// AppRole authentication
    AppRole {
        /// Role ID
        role_id: String,
        /// Secret ID
        secret_id: String,
        /// Mount path for AppRole auth
        #[serde(default = "default_approle_mount")]
        mount_path: String,
    },
    /// Kubernetes authentication
    Kubernetes {
        /// Service account token path
        #[serde(default = "default_k8s_token_path")]
        token_path: String,
        /// Kubernetes role
        role: String,
        /// Mount path for Kubernetes auth
        #[serde(default = "default_k8s_mount")]
        mount_path: String,
    },
    /// AWS IAM authentication
    Aws {
        /// AWS region
        region: String,
        /// Vault role name
        role: String,
        /// Mount path for AWS auth
        #[serde(default = "default_aws_mount")]
        mount_path: String,
    },
}

impl std::fmt::Debug for VaultAuthConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VaultAuthConfig::Token { .. } => f
                .debug_struct("VaultAuthConfig::Token")
                .field("token", &"[REDACTED]")
                .finish(),
            VaultAuthConfig::AppRole {
                role_id,
                mount_path,
                ..
            } => f
                .debug_struct("VaultAuthConfig::AppRole")
                .field("role_id", role_id)
                .field("secret_id", &"[REDACTED]")
                .field("mount_path", mount_path)
                .finish(),
            VaultAuthConfig::Kubernetes {
                token_path,
                role,
                mount_path,
            } => f
                .debug_struct("VaultAuthConfig::Kubernetes")
                .field("token_path", token_path)
                .field("role", role)
                .field("mount_path", mount_path)
                .finish(),
            VaultAuthConfig::Aws {
                region,
                role,
                mount_path,
            } => f
                .debug_struct("VaultAuthConfig::Aws")
                .field("region", region)
                .field("role", role)
                .field("mount_path", mount_path)
                .finish(),
        }
    }
}

/// Vault TLS configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct VaultTlsConfig {
    /// Skip TLS certificate verification (insecure)
    #[serde(default)]
    pub skip_verify: bool,
    /// Path to CA certificate file
    pub ca_cert: Option<PathBuf>,
    /// Path to client certificate file
    pub client_cert: Option<PathBuf>,
    /// Path to client private key file
    pub client_key: Option<PathBuf>,
}

/// Vault connection configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VaultConnectionConfig {
    /// Maximum number of connections in the pool
    #[serde(default = "default_max_connections")]
    pub max_connections: usize,
    /// Connection timeout in seconds
    #[serde(default = "default_connection_timeout")]
    pub connection_timeout_seconds: u64,
    /// Request timeout in seconds
    #[serde(default = "default_request_timeout")]
    pub request_timeout_seconds: u64,
}

impl Default for VaultConnectionConfig {
    fn default() -> Self {
        Self {
            max_connections: default_max_connections(),
            connection_timeout_seconds: default_connection_timeout(),
            request_timeout_seconds: default_request_timeout(),
        }
    }
}

/// Configuration for file-based secrets backend
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileConfig {
    /// Path to the secrets file or directory
    pub path: PathBuf,
    /// File format for secrets storage
    #[serde(default = "default_file_format")]
    pub format: FileFormat,
    /// Encryption configuration
    #[serde(default)]
    pub encryption: FileEncryptionConfig,
    /// File permissions (Unix only)
    pub permissions: Option<u32>,
    /// Watch for file changes and reload
    #[serde(default)]
    pub watch_for_changes: bool,
    /// Backup configuration
    #[serde(default)]
    pub backup: FileBackupConfig,
}

/// Supported file formats for secrets storage
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FileFormat {
    /// JSON format
    Json,
    /// YAML format
    Yaml,
    /// TOML format
    Toml,
    /// Plain text (key=value pairs)
    Env,
}

/// File encryption configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileEncryptionConfig {
    /// Enable encryption of secrets file
    #[serde(default)]
    pub enabled: bool,
    /// Encryption algorithm
    #[serde(default = "default_encryption_algorithm")]
    pub algorithm: String,
    /// Key derivation function
    #[serde(default = "default_kdf")]
    pub kdf: String,
    /// Key provider configuration
    #[serde(default)]
    pub key: FileKeyConfig,
}

/// Configuration for encryption key retrieval
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileKeyConfig {
    /// Key provider type
    #[serde(default = "default_key_provider")]
    pub provider: String,
    /// Environment variable containing encryption key (for 'env' provider)
    pub env_var: Option<String>,
    /// Keychain service name (for 'os_keychain' provider)
    pub service: Option<String>,
    /// Keychain account name (for 'os_keychain' provider)
    pub account: Option<String>,
    /// Path to key file (for 'file' provider)
    pub file_path: Option<PathBuf>,
}

impl Default for FileKeyConfig {
    fn default() -> Self {
        Self {
            provider: default_key_provider(),
            env_var: None,
            service: None,
            account: None,
            file_path: None,
        }
    }
}

impl Default for FileEncryptionConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            algorithm: default_encryption_algorithm(),
            kdf: default_kdf(),
            key: FileKeyConfig::default(),
        }
    }
}

/// File backup configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileBackupConfig {
    /// Enable automatic backups
    #[serde(default)]
    pub enabled: bool,
    /// Directory for backup files
    pub backup_dir: Option<PathBuf>,
    /// Maximum number of backup files to keep
    #[serde(default = "default_max_backups")]
    pub max_backups: usize,
    /// Create backup before modifications
    #[serde(default = "default_backup_before_write")]
    pub backup_before_write: bool,
}

impl Default for FileBackupConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            backup_dir: None,
            max_backups: default_max_backups(),
            backup_before_write: default_backup_before_write(),
        }
    }
}

// Default value functions
fn default_timeout() -> u64 {
    30
}
fn default_max_retries() -> u32 {
    3
}
fn default_enable_cache() -> bool {
    true
}
fn default_cache_ttl() -> u64 {
    300
}
fn default_vault_mount() -> String {
    "secret".to_string()
}
fn default_vault_api_version() -> String {
    "v2".to_string()
}
fn default_approle_mount() -> String {
    "approle".to_string()
}
fn default_k8s_token_path() -> String {
    "/var/run/secrets/kubernetes.io/serviceaccount/token".to_string()
}
fn default_k8s_mount() -> String {
    "kubernetes".to_string()
}
fn default_aws_mount() -> String {
    "aws".to_string()
}
fn default_max_connections() -> usize {
    10
}
fn default_connection_timeout() -> u64 {
    10
}
fn default_request_timeout() -> u64 {
    30
}
fn default_file_format() -> FileFormat {
    FileFormat::Json
}
fn default_encryption_algorithm() -> String {
    "AES-256-GCM".to_string()
}
fn default_kdf() -> String {
    "PBKDF2".to_string()
}
fn default_key_provider() -> String {
    "env".to_string()
}
fn default_max_backups() -> usize {
    5
}
fn default_backup_before_write() -> bool {
    true
}

impl SecretsConfig {
    /// Create a Vault configuration with token authentication
    pub fn vault_with_token(url: String, token: String) -> Self {
        Self {
            backend: SecretsBackend::Vault(VaultConfig {
                url,
                auth: VaultAuthConfig::Token { token },
                namespace: None,
                mount_path: default_vault_mount(),
                api_version: default_vault_api_version(),
                tls: VaultTlsConfig::default(),
                connection: VaultConnectionConfig::default(),
            }),
            common: CommonSecretsConfig::default(),
        }
    }

    /// Create a file-based configuration with JSON format
    pub fn file_json(path: PathBuf) -> Self {
        Self {
            backend: SecretsBackend::File(FileConfig {
                path,
                format: FileFormat::Json,
                encryption: FileEncryptionConfig::default(),
                permissions: Some(0o600),
                watch_for_changes: false,
                backup: FileBackupConfig::default(),
            }),
            common: CommonSecretsConfig::default(),
        }
    }

    /// Get the backend type as a string
    pub fn backend_type(&self) -> &'static str {
        match &self.backend {
            SecretsBackend::Vault(_) => "vault",
            SecretsBackend::File(_) => "file",
        }
    }

    /// Get timeout as Duration
    pub fn timeout(&self) -> Duration {
        Duration::from_secs(self.common.timeout_seconds)
    }

    /// Get cache TTL as Duration
    pub fn cache_ttl(&self) -> Duration {
        Duration::from_secs(self.common.cache_ttl_seconds)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_vault_config_creation() {
        let config = SecretsConfig::vault_with_token(
            "https://vault.example.com".to_string(),
            "hvs.token123".to_string(),
        );

        assert_eq!(config.backend_type(), "vault");
        if let SecretsBackend::Vault(vault_config) = &config.backend {
            assert_eq!(vault_config.url, "https://vault.example.com");
            if let VaultAuthConfig::Token { token } = &vault_config.auth {
                assert_eq!(token, "hvs.token123");
            } else {
                panic!("Expected token auth");
            }
        } else {
            panic!("Expected vault backend");
        }
    }

    #[test]
    fn test_file_config_creation() {
        let path = PathBuf::from("/etc/secrets/app.json");
        let config = SecretsConfig::file_json(path.clone());

        assert_eq!(config.backend_type(), "file");
        if let SecretsBackend::File(file_config) = &config.backend {
            assert_eq!(file_config.path, path);
            assert!(matches!(file_config.format, FileFormat::Json));
        } else {
            panic!("Expected file backend");
        }
    }

    #[test]
    fn test_common_config_defaults() {
        let config = CommonSecretsConfig::default();
        assert_eq!(config.timeout_seconds, 30);
        assert_eq!(config.max_retries, 3);
        assert!(config.enable_cache);
        assert_eq!(config.cache_ttl_seconds, 300);
    }

    #[test]
    fn test_timeout_conversion() {
        let config = SecretsConfig::file_json(PathBuf::from("/test"));
        assert_eq!(config.timeout(), Duration::from_secs(30));
        assert_eq!(config.cache_ttl(), Duration::from_secs(300));
    }
}