OXYGENHUB
◆ v0.2.0 oxygenflow / crates / flow / src / home.rs
13.0 KiB · Rust · last changed Keyless step 3, runner: sign receipts with a key the hub certifies per job 18 days ago source blame history raw
e0918b88 Andy McCall 1
//! `$FLOW_HOME` (default `~/.local/share/flow`): the pinned parts of each
2
//! isolation tier, rootfs images by hash, scratch space and the runner's
3
//! configuration, all described by `flow.toml`.
4
//!
5
//! ```toml
6
//! [microvm]
7
//! firecracker = { path = "bin/firecracker", blake3 = "…" }
8
//! kernel = { path = "kernel/vmlinux", blake3 = "…" }
9
//! init = { path = "bin/flow-init", blake3 = "…" }
10
//!
11
//! [runner]                       # only for `flow runner`
12
//! hub = "https://hub.example:7343"
13
//! token = "…"                    # a runner token from the hub's [flow] runner_tokens
14
//! ca = "/path/to/hub-ca.pem"     # when the hub's certificate is self-signed
15
//! name = "earth-1"
16
//! ```
47c1d64d Andy McCall ↶ 17
//!
18
//! A runner signs its receipts with a composite key kept beside `flow.toml`
19
//! (`runner.key`, `runner.identity`), made on first start.
e0918b88 Andy McCall 20
21
use anyhow::{bail, Context, Result};
22
use serde::Deserialize;
23
use std::collections::HashMap;
24
use std::path::{Path, PathBuf};
25
use std::sync::Mutex;
26
27
#[derive(Clone, Debug, Deserialize)]
28
pub struct Pinned {
29
    pub path: PathBuf,
30
    pub blake3: String,
31
}
32
33
#[derive(Clone, Debug, Deserialize)]
34
pub struct MicrovmConfig {
35
    pub firecracker: Pinned,
36
    pub kernel: Pinned,
37
    pub init: Pinned,
38
}
39
f98a8f78 Andy McCall ↶ 40
/// Where `flow runner register` keeps the runner's hub and credential.
41
pub const RUNNER_TOML: &str = "runner.toml";
42
e0918b88 Andy McCall 43
#[derive(Clone, Debug, Deserialize)]
44
pub struct RunnerConfig {
45
    pub hub: String,
46
    pub token: String,
47
    pub ca: Option<PathBuf>,
48
    pub name: Option<String>,
bb643c25 Andy McCall ↶ 49
    /// Jobs run at once (default 1).
50
    #[serde(default)]
51
    pub max_jobs: Option<usize>,
f98a8f78 Andy McCall ↶ 52
    /// Labels the runner offers, e.g. `gpu`, `big-disk`.
53
    #[serde(default)]
54
    pub labels: Vec<String>,
bb643c25 Andy McCall ↶ 55
    /// Memory (MiB) and vCPUs the jobs running at once may use together.
56
    #[serde(default)]
57
    pub memory_mib: Option<u32>,
58
    #[serde(default)]
59
    pub cpus: Option<u32>,
b14aeaae Andy McCall ↶ 60
    /// Sharing images with other runners (docs/jetstream.md §8.1): absent,
61
    /// the runner neither serves nor asks peers.
62
    #[serde(default)]
63
    pub swarm: Option<SwarmConfig>,
d60aac6c Andy McCall ↶ 64
    /// The build cache's size limit in GiB (#28; default 64).
65
    #[serde(default)]
66
    pub cache_gb: Option<u64>,
ea81796b Andy McCall ↶ 67
    /// Let microVM jobs reach the hosts their sandbox allows, through this
68
    /// runner (oxygenflow#55); off unless set. The runner then offers the
69
    /// `egress` label, which such jobs need.
70
    #[serde(default)]
71
    pub egress: bool,
35f7a849 Andy McCall ↶ 72
    /// Sign each job's receipt with a fresh key the hub certifies for that
73
    /// job, just before signing (keyless, oxygenhub#241), rather than with
74
    /// the runner's own key; off unless set. When the hub cannot certify,
75
    /// the runner's key signs, and the job's log says why.
76
    #[serde(default)]
77
    pub keyless: bool,
ea81796b Andy McCall ↶ 78
}
79
80
impl RunnerConfig {
81
    /// The labels offered to the hub: the configured ones, and `egress`
82
    /// when egress is on.
83
    pub fn offered_labels(&self) -> Vec<String> {
84
        let mut l = self.labels.clone();
85
        if self.egress && !l.iter().any(|x| x == flow_core::EGRESS_LABEL) {
86
            l.push(flow_core::EGRESS_LABEL.to_string());
87
        }
88
        l
89
    }
b14aeaae Andy McCall ↶ 90
}
91
92
/// `[runner.swarm]` in flow.toml, or `[swarm]` in runner.toml.
93
#[derive(Clone, Debug, Deserialize)]
94
pub struct SwarmConfig {
95
    /// Where peers reach this runner, e.g. `0.0.0.0:7401`.
96
    pub listen: String,
97
    /// The address peers are given (default: `listen`).
98
    #[serde(default)]
99
    pub advertise: Option<String>,
100
    /// Peers are only ever in the same site.
101
    #[serde(default)]
102
    pub site: String,
103
    /// The most this runner sends to peers, MiB a second (default 50).
104
    #[serde(default)]
105
    pub upload_mib_s: Option<u32>,
e0918b88 Andy McCall 106
}
107
108
#[derive(Clone, Debug, Default, Deserialize)]
109
pub struct Config {
110
    pub microvm: Option<MicrovmConfig>,
111
    pub runner: Option<RunnerConfig>,
112
}
113
114
pub struct Home {
115
    pub root: PathBuf,
116
    pub config: Config,
117
    /// Files already verified, by path, with the (len, mtime) they had then.
118
    verified: Mutex<HashMap<PathBuf, (u64, std::time::SystemTime)>>,
119
}
120
121
impl Home {
122
    pub fn locate(explicit: Option<&Path>) -> Result<Home> {
123
        let root = match explicit {
124
            Some(p) => p.to_path_buf(),
125
            None => match std::env::var_os("FLOW_HOME") {
126
                Some(p) => PathBuf::from(p),
127
                None => PathBuf::from(std::env::var_os("HOME").context("HOME is not set")?).join(".local/share/flow"),
128
            },
129
        };
130
        let file = root.join("flow.toml");
f98a8f78 Andy McCall ↶ 131
        let mut config: Config = if file.is_file() {
e0918b88 Andy McCall 132
            let text = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
133
            toml::from_str(&text).with_context(|| format!("parse {}", file.display()))?
134
        } else {
135
            Config::default()
136
        };
f98a8f78 Andy McCall ↶ 137
        // `flow runner register` writes the runner's hub and credential to
138
        // runner.toml, which stands in for a [runner] section flow.toml lacks.
139
        let registered = root.join(RUNNER_TOML);
140
        if config.runner.is_none() && registered.is_file() {
141
            let text = std::fs::read_to_string(&registered).with_context(|| format!("read {}", registered.display()))?;
142
            config.runner = Some(toml::from_str(&text).with_context(|| format!("parse {}", registered.display()))?);
143
        }
e0918b88 Andy McCall 144
        for d in ["cas", "work", "repos"] {
145
            std::fs::create_dir_all(root.join(d)).with_context(|| format!("create {}", root.join(d).display()))?;
146
        }
147
        Ok(Home { root, config, verified: Mutex::new(HashMap::new()) })
148
    }
149
150
    pub fn resolve(&self, p: &Path) -> PathBuf {
151
        if p.is_absolute() {
152
            p.to_path_buf()
153
        } else {
154
            self.root.join(p)
155
        }
156
    }
157
158
    /// Where a rootfs image with this hash lives.
159
    pub fn rootfs(&self, hash: &str) -> PathBuf {
160
        self.root.join("cas").join(format!("{hash}.ext4"))
161
    }
162
1abadd4a Andy McCall ↶ 163
    /// An image's manifest (`cas/<hash>.json`): what `flow rootfs import`
164
    /// found out about it.
165
    pub fn image_manifest(&self, hash: &str) -> PathBuf {
166
        self.root.join("cas").join(format!("{hash}.json"))
167
    }
168
0077c748 Andy McCall ↶ 169
    /// The architecture an image is for: as its manifest records, else
170
    /// read from the image's own shell (spec §11.2) and recorded, so an
171
    /// image fetched or imported without one is read once and a runner
172
    /// declines what it cannot run instead of failing it. `None` when the
173
    /// image is not here or names no architecture.
1abadd4a Andy McCall ↶ 174
    pub fn image_arch(&self, hash: &str) -> Option<String> {
0077c748 Andy McCall ↶ 175
        let path = self.image_manifest(hash);
176
        let mut v: serde_json::Value =
177
            std::fs::read_to_string(&path).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_else(|| serde_json::json!({}));
178
        if let Some(a) = v["arch"].as_str() {
179
            return Some(a.to_string());
180
        }
181
        let image = self.rootfs(hash);
182
        if v.get("arch_read_ms").is_some() || !image.is_file() {
183
            return None;
184
        }
185
        let arch = jet::rootfs::arch_of_file(&image);
186
        let o = v.as_object_mut()?;
187
        if let Some(a) = arch {
188
            o.insert("arch".into(), a.into());
189
        }
190
        let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
191
        o.insert("arch_read_ms".into(), now.into());
192
        let tmp = path.with_extension("json.part");
193
        if std::fs::write(&tmp, v.to_string()).is_ok() {
194
            let _ = std::fs::rename(&tmp, &path);
195
        }
196
        arch.map(String::from)
1abadd4a Andy McCall ↶ 197
    }
198
199
    /// Every image with a known architecture (spec §11.2).
200
    pub fn image_archs(&self) -> std::collections::BTreeMap<String, String> {
201
        self.images().into_iter().filter_map(|h| self.image_arch(&h).map(|a| (h, a))).collect()
202
    }
203
8c0a4e3a Andy McCall ↶ 204
    /// The rootfs images this home holds: the hashes of `cas/*.ext4`.
205
    pub fn images(&self) -> Vec<String> {
206
        let Ok(dir) = std::fs::read_dir(self.root.join("cas")) else {
207
            return Vec::new();
208
        };
209
        let mut out: Vec<String> = dir
210
            .filter_map(|e| {
211
                let name = e.ok()?.file_name().into_string().ok()?;
212
                let hash = name.strip_suffix(".ext4")?;
213
                (hash.len() == 64 && hash.chars().all(|c| c.is_ascii_hexdigit())).then(|| hash.to_string())
214
            })
215
            .collect();
216
        out.sort();
217
        out
218
    }
219
e0918b88 Andy McCall 220
    /// A pinned file, checked against its BLAKE3 before use (again only
221
    /// when its size or modification time changed since).
222
    pub fn verified(&self, path: &Path, blake3_hex: &str) -> Result<PathBuf> {
223
        let meta = std::fs::metadata(path).with_context(|| format!("{} is missing", path.display()))?;
224
        let stamp = (meta.len(), meta.modified()?);
225
        if self.verified.lock().unwrap().get(path) == Some(&stamp) {
226
            return Ok(path.to_path_buf());
227
        }
ab3204b9 Andy McCall ↶ 228
        let mut got = hash_file(path)?;
e0918b88 Andy McCall 229
        if got != blake3_hex {
ab3204b9 Andy McCall ↶ 230
            // The read may have come from bad cached pages rather than the
231
            // disk (oxygenflow#22: a RAM fault on Earth failed every job for
232
            // hours while the file was intact): drop the file's pages and
233
            // read it again from the disk before giving up.
234
            drop_cached(path);
235
            let again = hash_file(path)?;
236
            if again == blake3_hex {
237
                eprintln!(
238
                    "warning: {} hashed {got} from the page cache but {again} from the disk: the cached copy was bad (check this machine's memory)",
239
                    path.display()
240
                );
241
            }
242
            got = again;
243
        }
244
        if got != blake3_hex {
e0918b88 Andy McCall 245
            bail!("{} has BLAKE3 {got}, but {blake3_hex} is pinned", path.display());
246
        }
247
        self.verified.lock().unwrap().insert(path.to_path_buf(), stamp);
248
        Ok(path.to_path_buf())
ab3204b9 Andy McCall ↶ 249
    }
250
}
251
252
/// Ask the kernel to forget a file's cached pages, so the next read comes
253
/// from the disk. Best effort: dirty pages and other platforms stay.
254
fn drop_cached(path: &Path) {
255
    #[cfg(target_os = "linux")]
256
    if let Ok(f) = std::fs::File::open(path) {
257
        use std::os::fd::AsRawFd;
258
        // SAFETY: a valid descriptor; the advice only affects caching.
259
        unsafe {
260
            libc::posix_fadvise(f.as_raw_fd(), 0, 0, libc::POSIX_FADV_DONTNEED);
261
        }
e0918b88 Andy McCall 262
    }
ab3204b9 Andy McCall ↶ 263
    #[cfg(not(target_os = "linux"))]
264
    let _ = path;
e0918b88 Andy McCall 265
}
266
267
pub fn hash_file(path: &Path) -> Result<String> {
268
    let mut h = blake3::Hasher::new();
269
    h.update_reader(std::fs::File::open(path).with_context(|| format!("open {}", path.display()))?)?;
270
    Ok(h.finalize().to_hex().to_string())
47c1d64d Andy McCall ↶ 271
}
272
273
/// The key a runner signs receipts with (Oxygen spec §14.6).
274
pub struct RunnerKey {
275
    pub identity: oxy_core::identity::Identity,
276
    pub secret: oxy_core::identity::SecretKey,
277
}
278
279
impl Home {
280
    /// The runner's key, made on first use as `runner.key` (owner-only)
281
    /// and `runner.identity`, named `name`.
282
    pub fn runner_key(&self, name: &str) -> Result<RunnerKey> {
283
        use oxy_core::identity::{Identity, SecretKey};
284
        let key_path = self.root.join("runner.key");
285
        let id_path = self.root.join("runner.identity");
286
        if key_path.exists() {
287
            let (key, secret) = SecretKey::decode(&std::fs::read(&key_path)?).context("runner.key")?;
288
            let identity = Identity::decode(&std::fs::read(&id_path)?).context("runner.identity")?;
289
            if identity.hash() != key {
290
                bail!("runner.identity does not belong to runner.key");
291
            }
292
            return Ok(RunnerKey { identity, secret });
293
        }
294
        let secret = SecretKey::generate();
295
        let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
296
        let identity = secret.identity(&format!("{name} (OxygenFlow runner)"), "", now);
297
        std::fs::write(&id_path, identity.encode())?;
298
        let tmp = self.root.join("runner.key.tmp");
299
        {
300
            use std::io::Write;
301
            use std::os::unix::fs::OpenOptionsExt;
302
            let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&tmp)?;
303
            f.write_all(&secret.encode(&identity.hash()))?;
304
            f.sync_all()?;
305
        }
306
        std::fs::rename(&tmp, &key_path)?;
307
        Ok(RunnerKey { identity, secret })
308
    }
309
}
310
311
#[cfg(test)]
312
mod tests {
313
    use super::*;
314
315
    #[test]
316
    fn the_runner_key_is_made_once_and_kept_private() {
317
        use std::os::unix::fs::PermissionsExt;
318
        let dir = tempfile::tempdir().unwrap();
319
        let home = Home::locate(Some(dir.path())).unwrap();
320
        let a = home.runner_key("earth-1").unwrap();
321
        assert_eq!(a.identity.name, "earth-1 (OxygenFlow runner)");
322
        let mode = std::fs::metadata(dir.path().join("runner.key")).unwrap().permissions().mode();
323
        assert_eq!(mode & 0o777, 0o600);
324
        let b = home.runner_key("renamed").unwrap();
325
        assert_eq!(a.identity, b.identity, "the same key after a restart");
326
        let sig = b.secret.sign(oxy_core::identity::Domain::Attest, &b.identity.hash(), &oxy_core::hash::ObjectRef([1; 32]));
327
        oxy_core::identity::verify(&a.identity, &sig, oxy_core::identity::Domain::Attest, &oxy_core::hash::ObjectRef([1; 32])).unwrap();
328
    }
e0918b88 Andy McCall 329
}