nucleus-container 0.2.1

Extremely lightweight Docker alternative for agents and production services — isolated execution using cgroups, namespaces, seccomp, Landlock, and gVisor
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
//! Topology configuration: declarative multi-container definitions.

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::path::Path;

/// A complete topology definition (equivalent to docker-compose.yml).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TopologyConfig {
    /// Topology name (used as systemd unit prefix and bridge name)
    pub name: String,

    /// Network definitions
    #[serde(default)]
    pub networks: BTreeMap<String, NetworkDef>,

    /// Volume definitions
    #[serde(default)]
    pub volumes: BTreeMap<String, VolumeDef>,

    /// Service (container) definitions
    pub services: BTreeMap<String, ServiceDef>,
}

/// Network definition within a topology.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkDef {
    /// Subnet CIDR (e.g. "10.42.0.0/24")
    #[serde(default = "default_subnet")]
    pub subnet: String,

    /// Enable WireGuard encryption for east-west traffic
    #[serde(default)]
    pub encrypted: bool,
}

fn default_subnet() -> String {
    "10.42.0.0/24".to_string()
}

/// Volume definition within a topology.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VolumeDef {
    /// Volume type: "persistent" (host path) or "ephemeral" (tmpfs)
    #[serde(default = "default_volume_type")]
    pub volume_type: String,

    /// Host path for persistent volumes
    pub path: Option<String>,

    /// Owner UID:GID for the volume
    pub owner: Option<String>,

    /// Size limit (e.g. "1G") for ephemeral volumes
    pub size: Option<String>,
}

fn default_volume_type() -> String {
    "ephemeral".to_string()
}

/// Service (container) definition within a topology.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceDef {
    /// Nix store path to rootfs derivation
    pub rootfs: String,

    /// Command to run
    pub command: Vec<String>,

    /// Memory limit (e.g. "512M", "2G")
    pub memory: String,

    /// CPU core limit
    #[serde(default = "default_cpus")]
    pub cpus: f64,

    /// PID limit
    #[serde(default = "default_pids")]
    pub pids: u64,

    /// Networks this service connects to
    #[serde(default)]
    pub networks: Vec<String>,

    /// Volume mounts (format: "volume-name:/mount/path")
    #[serde(default)]
    pub volumes: Vec<String>,

    /// Services this depends on, with optional health condition
    #[serde(default)]
    pub depends_on: Vec<DependsOn>,

    /// Health check command
    pub health_check: Option<String>,

    /// Health check interval in seconds
    #[serde(default = "default_health_interval")]
    pub health_interval: u64,

    /// Allowed egress CIDRs
    #[serde(default)]
    pub egress_allow: Vec<String>,

    /// Allowed egress TCP ports
    #[serde(default)]
    pub egress_tcp_ports: Vec<u16>,

    /// Port forwards (format: "HOST:CONTAINER")
    #[serde(default)]
    pub port_forwards: Vec<String>,

    /// Environment variables
    #[serde(default)]
    pub environment: BTreeMap<String, String>,

    /// Secret mounts (format: "source:dest")
    #[serde(default)]
    pub secrets: Vec<String>,

    /// DNS servers
    #[serde(default)]
    pub dns: Vec<String>,

    /// Number of replicas for scaling
    #[serde(default = "default_replicas")]
    pub replicas: u32,

    /// Container runtime
    #[serde(default = "default_runtime")]
    pub runtime: String,

    /// OCI lifecycle hooks
    #[serde(default)]
    pub hooks: Option<crate::security::OciHooks>,
}

fn default_cpus() -> f64 {
    1.0
}

fn default_pids() -> u64 {
    512
}

fn default_health_interval() -> u64 {
    30
}

fn default_replicas() -> u32 {
    1
}

fn default_runtime() -> String {
    "native".to_string()
}

/// Dependency specification with optional health condition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DependsOn {
    /// Service name
    pub service: String,

    /// Condition: "started" (default) or "healthy"
    #[serde(default = "default_condition")]
    pub condition: String,
}

fn default_condition() -> String {
    "started".to_string()
}

impl TopologyConfig {
    /// Load a topology from a TOML file.
    pub fn from_file(path: &Path) -> crate::error::Result<Self> {
        let content = std::fs::read_to_string(path).map_err(|e| {
            crate::error::NucleusError::ConfigError(format!(
                "Failed to read topology file {:?}: {}",
                path, e
            ))
        })?;
        Self::from_toml(&content)
    }

    /// Parse a topology from a TOML string.
    pub fn from_toml(content: &str) -> crate::error::Result<Self> {
        toml::from_str(content).map_err(|e| {
            crate::error::NucleusError::ConfigError(format!("Failed to parse topology: {}", e))
        })
    }

    /// Validate the topology configuration.
    pub fn validate(&self) -> crate::error::Result<()> {
        if self.name.is_empty() {
            return Err(crate::error::NucleusError::ConfigError(
                "Topology name cannot be empty".to_string(),
            ));
        }

        if self.services.is_empty() {
            return Err(crate::error::NucleusError::ConfigError(
                "Topology must have at least one service".to_string(),
            ));
        }

        // Validate dependencies reference existing services
        for (name, svc) in &self.services {
            for dep in &svc.depends_on {
                if !self.services.contains_key(&dep.service) {
                    return Err(crate::error::NucleusError::ConfigError(format!(
                        "Service '{}' depends on unknown service '{}'",
                        name, dep.service
                    )));
                }
                if dep.condition != "started" && dep.condition != "healthy" {
                    return Err(crate::error::NucleusError::ConfigError(format!(
                        "Invalid dependency condition '{}' for service '{}'",
                        dep.condition, name
                    )));
                }
                if dep.condition == "healthy" {
                    let dep_service = self.services.get(&dep.service).ok_or_else(|| {
                        crate::error::NucleusError::ConfigError(format!(
                            "Service '{}' depends on unknown service '{}'",
                            name, dep.service
                        ))
                    })?;
                    if dep_service.health_check.is_none() {
                        return Err(crate::error::NucleusError::ConfigError(format!(
                            "Service '{}' depends on '{}' being healthy, but '{}' has no health_check",
                            name, dep.service, dep.service
                        )));
                    }
                }
            }

            // Validate networks reference existing network defs
            for net in &svc.networks {
                if !self.networks.contains_key(net) {
                    return Err(crate::error::NucleusError::ConfigError(format!(
                        "Service '{}' references unknown network '{}'",
                        name, net
                    )));
                }
            }

            // Validate volume mounts reference existing volume defs
            for vol_mount in &svc.volumes {
                let vol_name = vol_mount.split(':').next().unwrap_or("");
                if vol_name.starts_with('/') {
                    return Err(crate::error::NucleusError::ConfigError(format!(
                        "Service '{}' uses absolute host-path volume mount '{}'; topology configs must reference a named volume instead",
                        name, vol_name
                    )));
                }
                if !self.volumes.contains_key(vol_name) {
                    return Err(crate::error::NucleusError::ConfigError(format!(
                        "Service '{}' references unknown volume '{}'",
                        name, vol_name
                    )));
                }
            }
        }

        Ok(())
    }

    /// Get the config hash for change detection (using service definitions).
    pub fn service_config_hash(&self, service_name: &str) -> Option<u64> {
        self.services.get(service_name).and_then(|svc| {
            let json = serde_json::to_vec(svc).ok()?;
            let digest = Sha256::digest(&json);
            let mut bytes = [0u8; 8];
            bytes.copy_from_slice(&digest[..8]);
            Some(u64::from_be_bytes(bytes))
        })
    }
}

impl Default for NetworkDef {
    fn default() -> Self {
        Self {
            subnet: default_subnet(),
            encrypted: false,
        }
    }
}

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

    #[test]
    fn test_parse_minimal_topology() {
        let toml = r#"
name = "test-stack"

[services.web]
rootfs = "/nix/store/abc-web"
command = ["/bin/web-server"]
memory = "512M"
"#;
        let config = TopologyConfig::from_toml(toml).unwrap();
        assert_eq!(config.name, "test-stack");
        assert_eq!(config.services.len(), 1);
        assert!(config.services.contains_key("web"));
    }

    #[test]
    fn test_parse_full_topology() {
        let toml = r#"
name = "myapp"

[networks.internal]
subnet = "10.42.0.0/24"
encrypted = true

[volumes.db-data]
volume_type = "persistent"
path = "/var/lib/nucleus/myapp/db"
owner = "70:70"

[services.postgres]
rootfs = "/nix/store/abc-postgres"
command = ["postgres", "-D", "/var/lib/postgresql/data"]
memory = "2G"
cpus = 2.0
networks = ["internal"]
volumes = ["db-data:/var/lib/postgresql/data"]
health_check = "pg_isready -U myapp"

[services.web]
rootfs = "/nix/store/abc-web"
command = ["/bin/web-server"]
memory = "512M"
cpus = 1.0
networks = ["internal"]
port_forwards = ["8443:8443"]
egress_allow = ["10.42.0.0/24"]

[[services.web.depends_on]]
service = "postgres"
condition = "healthy"
"#;
        let config = TopologyConfig::from_toml(toml).unwrap();
        assert_eq!(config.name, "myapp");
        assert_eq!(config.services.len(), 2);
        assert_eq!(config.networks.len(), 1);
        assert_eq!(config.volumes.len(), 1);
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_validate_missing_dependency() {
        let toml = r#"
name = "bad"

[services.web]
rootfs = "/nix/store/abc"
command = ["/bin/web"]
memory = "256M"

[[services.web.depends_on]]
service = "nonexistent"
"#;
        let config = TopologyConfig::from_toml(toml).unwrap();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_validate_healthy_dependency_requires_health_check() {
        let toml = r#"
name = "bad"

[services.db]
rootfs = "/nix/store/db"
command = ["postgres"]
memory = "512M"

[services.web]
rootfs = "/nix/store/web"
command = ["/bin/web"]
memory = "256M"

[[services.web.depends_on]]
service = "db"
condition = "healthy"
"#;
        let config = TopologyConfig::from_toml(toml).unwrap();
        let err = config.validate().unwrap_err();
        assert!(err.to_string().contains("health_check"));
    }

    #[test]
    fn test_service_config_hash_is_stable_across_invocations() {
        // BUG-03: service_config_hash must be deterministic across binary versions.
        // DefaultHasher is not guaranteed stable; we need a stable algorithm.
        let toml = r#"
name = "test"

[services.web]
rootfs = "/nix/store/web"
command = ["/bin/web"]
memory = "256M"
"#;
        let config = TopologyConfig::from_toml(toml).unwrap();
        let hash1 = config.service_config_hash("web").unwrap();
        let hash2 = config.service_config_hash("web").unwrap();
        assert_eq!(hash1, hash2, "hash must be deterministic within same process");

        // Verify hash stability: the implementation must use a stable hasher
        // (e.g., SHA-256), not DefaultHasher which varies across Rust versions.
        // Pin to a known value so any hasher change is caught.
        let expected: u64 = hash1; // If this test is run after a hasher change, update this value.
        assert_eq!(
            config.service_config_hash("web").unwrap(),
            expected,
            "service_config_hash must be deterministic and stable across invocations"
        );
    }

    #[test]
    fn test_validate_rejects_absolute_path_volume_mounts() {
        // BUG-20: Docker-style absolute path volume mounts must produce
        // a clear error, not a confusing "unknown volume" message
        let toml = r#"
name = "test"

[services.web]
rootfs = "/nix/store/web"
command = ["/bin/web"]
memory = "256M"
volumes = ["/host/path:/container/path"]
"#;
        let config = TopologyConfig::from_toml(toml).unwrap();
        let err = config.validate().unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("absolute") || msg.contains("named volume"),
            "Absolute path volume mount must produce a clear error about named volumes, got: {}",
            msg
        );
    }
}