lonca-daemon 0.2.1

The Lonca daemon: the single writer every operation goes through (decide, sign, log, apply)
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
//! The daemon's home directory.
//!
//! ```text
//! $LONCA_HOME/
//!   daemon.key        ed25519 signing key (0600)
//!   daemon.next.key   the key a rotation in progress moves to (0600)
//!   tokens.json       sha256(token) -> agent session or human session (0600)
//!   lonca.sock        Unix socket
//!   repos/<name>.git  bare Git stores
//!   scratch/          verifier work trees
//!   backups/          bundles written by `repo.backup` (or $LONCA_BACKUPS)
//! ```
//!
//! In hardened mode the directory belongs to a dedicated system user, so
//! agents running as the developer can not read the key or write the stores.
//! The backups directory is the one place the developer's group may read,
//! so it lives outside the home there (`--backups`).

use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

use lonca_core::canonical::{random_bytes, sha256_hex};
use lonca_core::keys::KeyPair;

use crate::sys::current_uid;
use lonca_core::{Error, Result};
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug)]
pub struct Home {
    pub root: PathBuf,
    backups: Option<PathBuf>,
}

impl Home {
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            root: root.into(),
            backups: None,
        }
    }

    /// `$LONCA_HOME`, else `~/.lonca`; backups in `$LONCA_BACKUPS` if set.
    pub fn from_env() -> Self {
        let home = match std::env::var_os("LONCA_HOME") {
            Some(p) => Self::new(p),
            None => {
                let home = std::env::var_os("HOME")
                    .map(PathBuf::from)
                    .unwrap_or_else(|| PathBuf::from("."));
                Self::new(home.join(".lonca"))
            }
        };
        match std::env::var_os("LONCA_BACKUPS") {
            Some(p) => home.with_backups(p),
            None => home,
        }
    }

    /// Where `repo.backup` writes its bundles instead of `backups/` in the
    /// home: in hardened mode a directory the developer's group can read.
    pub fn with_backups(mut self, dir: impl Into<PathBuf>) -> Self {
        self.backups = Some(dir.into());
        self
    }

    pub fn backups(&self) -> PathBuf {
        self.backups
            .clone()
            .unwrap_or_else(|| self.root.join("backups"))
    }

    /// Creates the home, or checks the one there: it must belong to this
    /// process's user, and it is closed to everyone else (mode 0700).
    pub fn ensure(&self) -> Result<()> {
        fs::create_dir_all(self.repos())?;
        owned_by(&self.root, current_uid())?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&self.root, fs::Permissions::from_mode(0o700))?;
        }
        Ok(())
    }

    /// `$LONCA_SOCKET`, else `lonca.sock` in the home. Unix socket paths are
    /// limited to about 100 bytes, so long homes need `LONCA_SOCKET`.
    pub fn socket(&self) -> PathBuf {
        std::env::var_os("LONCA_SOCKET")
            .map(PathBuf::from)
            .unwrap_or_else(|| self.root.join("lonca.sock"))
    }

    pub fn key_path(&self) -> PathBuf {
        self.root.join("daemon.key")
    }

    pub fn repos(&self) -> PathBuf {
        self.root.join("repos")
    }

    pub fn repo_path(&self, name: &str) -> PathBuf {
        self.repos().join(format!("{name}.git"))
    }

    /// The daemon's copies of bundles from the import directory, each
    /// removed after its fetch; emptied at every start.
    pub fn imports(&self) -> PathBuf {
        self.root.join("imports")
    }

    pub fn scratch(&self) -> PathBuf {
        self.root.join("scratch")
    }

    pub fn tokens_path(&self) -> PathBuf {
        self.root.join("tokens.json")
    }

    /// Written by `lonca-audit --freeze-flag` when it finds a problem.
    pub fn freeze_flag(&self, repo: &str) -> PathBuf {
        self.root.join("freeze").join(repo)
    }

    pub fn load_key(&self) -> Result<KeyPair> {
        KeyPair::load_or_create(&self.key_path(), current_uid())
    }

    /// Where a rotation keeps the new key until every repository uses it.
    pub fn next_key_path(&self) -> PathBuf {
        self.root.join("daemon.next.key")
    }

    /// The current key and the key of an unfinished rotation. A crash
    /// between the two steps of [`Home::promote_next_key`] leaves only the
    /// next key; it is the current one then.
    pub fn load_keys(&self) -> Result<(KeyPair, Option<KeyPair>)> {
        let next = self.next_key_path();
        if !self.key_path().exists() && next.exists() {
            fs::rename(&next, self.key_path())?;
        }
        let current = self.load_key()?;
        let next = if next.exists() {
            Some(KeyPair::load(&next, current_uid())?)
        } else {
            None
        };
        Ok((current, next))
    }

    /// The next key, created on first use.
    pub fn load_or_create_next_key(&self) -> Result<KeyPair> {
        KeyPair::load_or_create(&self.next_key_path(), current_uid())
    }

    /// Makes the next key the current one once no repository uses the
    /// current key. The old secret is deleted: the entries it signed stay
    /// verifiable through its public key in the log, and nothing may be
    /// signed with it again.
    pub fn promote_next_key(&self) -> Result<()> {
        fs::remove_file(self.key_path())?;
        fs::rename(self.next_key_path(), self.key_path())?;
        Ok(())
    }
}

/// Refuses a home that another user owns: whoever owns it can replace the
/// key, the tokens and the stores, and a daemon would sign for them.
fn owned_by(root: &Path, uid: u32) -> Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        let owner = fs::metadata(root)?.uid();
        if owner != uid {
            return Err(Error::Invalid(format!(
                "daemon home {} belongs to uid {owner}, not to this daemon (uid {uid}); \
                 run the daemon as its owner, or give it a home of its own",
                root.display()
            )));
        }
    }
    let _ = (root, uid);
    Ok(())
}

/// What a token stands for. Agent entries predate human sessions and are
/// stored without a tag; the two shapes share no required field, so an
/// untagged enum reads both.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum TokenEntry {
    /// An agent session of one repository. `expires_ms` is the session's
    /// own end, from its log entry; entries written before it was stored
    /// have none, and the log says when they end.
    Agent {
        repo: String,
        session: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        expires_ms: Option<i64>,
    },
    /// A human session (`human.login`): the human proved presence with
    /// `key`, and the session is good wherever that key is enrolled.
    Human {
        human: String,
        key: String,
        expires_ms: i64,
    },
}

/// Session tokens. Only their SHA-256 is stored, never the token itself.
#[derive(Default)]
pub struct Tokens {
    path: Option<PathBuf>,
    map: BTreeMap<String, TokenEntry>,
}

impl Tokens {
    pub fn load(path: &Path) -> Result<Self> {
        let map = match fs::read(path) {
            Ok(b) => serde_json::from_slice(&b)?,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => BTreeMap::new(),
            Err(e) => return Err(e.into()),
        };
        Ok(Self {
            path: Some(path.to_path_buf()),
            map,
        })
    }

    /// A token for an agent session that ends at `expires_ms`.
    pub fn issue(&mut self, repo: &str, session: &str, expires_ms: i64) -> Result<String> {
        self.insert(
            "lonca_",
            TokenEntry::Agent {
                repo: repo.into(),
                session: session.into(),
                expires_ms: Some(expires_ms),
            },
        )
    }

    /// Replaces `old` with a new token for the same session, in one write:
    /// from then on only the new one works. `None` if `old` is unknown.
    pub fn rotate(&mut self, old: &str) -> Result<Option<String>> {
        let Some(entry) = self.map.remove(&sha256_hex(old.as_bytes())) else {
            return Ok(None);
        };
        let prefix = match entry {
            TokenEntry::Agent { .. } => "lonca_",
            TokenEntry::Human { .. } => "lonca_h_",
        };
        self.insert(prefix, entry).map(Some)
    }

    pub fn issue_human(&mut self, human: &str, key: &str, expires_ms: i64) -> Result<String> {
        self.insert(
            "lonca_h_",
            TokenEntry::Human {
                human: human.into(),
                key: key.into(),
                expires_ms,
            },
        )
    }

    fn insert(&mut self, prefix: &str, entry: TokenEntry) -> Result<String> {
        let token = format!("{prefix}{}", hex::encode(random_bytes::<32>()));
        self.map.insert(sha256_hex(token.as_bytes()), entry);
        self.save()?;
        Ok(token)
    }

    pub fn lookup(&self, token: &str) -> Option<&TokenEntry> {
        self.map.get(&sha256_hex(token.as_bytes()))
    }

    /// Drops one token (logout). Unknown tokens are not an error.
    pub fn revoke(&mut self, token: &str) -> Result<()> {
        if self.map.remove(&sha256_hex(token.as_bytes())).is_some() {
            self.save()?;
        }
        Ok(())
    }

    pub fn revoke_sessions(&mut self, repo: &str, sessions: &[String]) -> Result<()> {
        let before = self.map.len();
        self.map.retain(|_, e| match e {
            TokenEntry::Agent {
                repo: r, session, ..
            } => !(r == repo && sessions.contains(session)),
            TokenEntry::Human { .. } => true,
        });
        if self.map.len() != before {
            self.save()?;
        }
        Ok(())
    }

    /// Drops every token that no longer works at `now_ms`: human sessions
    /// past their end, and agent sessions past theirs or that `live` says
    /// are over (ended, expired with a parent, of a repository gone).
    pub fn sweep_expired(&mut self, now_ms: i64, live: impl Fn(&str, &str) -> bool) -> Result<()> {
        let before = self.map.len();
        self.map.retain(|_, e| match e {
            TokenEntry::Agent {
                repo,
                session,
                expires_ms,
            } => expires_ms.is_none_or(|end| end > now_ms) && live(repo, session),
            TokenEntry::Human { expires_ms, .. } => *expires_ms > now_ms,
        });
        if self.map.len() != before {
            self.save()?;
        }
        Ok(())
    }

    fn save(&self) -> Result<()> {
        let Some(path) = &self.path else {
            return Ok(());
        };
        let tmp = path.with_extension("tmp");
        let mut opts = fs::OpenOptions::new();
        opts.write(true).create(true).truncate(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            opts.mode(0o600);
        }
        let mut f = opts.open(&tmp)?;
        f.write_all(&serde_json::to_vec_pretty(&self.map)?)?;
        f.sync_all()?;
        fs::rename(&tmp, path).map_err(Error::from)
    }
}

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

    #[test]
    fn a_home_must_belong_to_the_daemon() {
        let dir = tempfile::tempdir().unwrap();
        let home = Home::new(dir.path().join("h"));
        home.ensure().unwrap();
        assert!(owned_by(&home.root, current_uid()).is_ok());
        let e = owned_by(&home.root, current_uid() + 1)
            .unwrap_err()
            .to_string();
        assert!(e.contains("belongs to uid"), "{e}");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = fs::metadata(&home.root).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o700);
        }
    }

    #[test]
    fn tokens_are_stored_as_hashes_and_both_kinds_survive_a_reload() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("tokens.json");
        // A file written before human sessions existed.
        std::fs::write(
            &path,
            format!(
                "{{\"{}\": {{\"repo\": \"demo\", \"session\": \"s0\"}}}}",
                sha256_hex(b"lonca_old")
            ),
        )
        .unwrap();
        let mut t = Tokens::load(&path).unwrap();
        let a = t.issue("demo", "s1", 5_000).unwrap();
        let h = t.issue_human("ayse", "ab", 2_000).unwrap();
        assert!(a.starts_with("lonca_") && h.starts_with("lonca_h_"));
        let text = std::fs::read_to_string(&path).unwrap();
        assert!(!text.contains(&a) && !text.contains(&h), "{text}");
        let t = Tokens::load(&path).unwrap();
        assert_eq!(
            t.lookup("lonca_old"),
            Some(&TokenEntry::Agent {
                repo: "demo".into(),
                session: "s0".into(),
                expires_ms: None,
            })
        );
        assert_eq!(
            t.lookup(&h),
            Some(&TokenEntry::Human {
                human: "ayse".into(),
                key: "ab".into(),
                expires_ms: 2_000
            })
        );
        let mut t = t;
        t.revoke_sessions("demo", &["s1".into()]).unwrap();
        assert!(t.lookup(&a).is_none() && t.lookup(&h).is_some());
        t.sweep_expired(1_999, |_, _| true).unwrap();
        assert!(t.lookup(&h).is_some());
        t.sweep_expired(2_000, |_, _| true).unwrap();
        assert!(t.lookup(&h).is_none());
        t.revoke("lonca_old").unwrap();
        t.revoke("lonca_old").unwrap();
        assert!(Tokens::load(&path).unwrap().lookup("lonca_old").is_none());
    }

    /// An agent token goes at its session's end, or when the log says the
    /// session is over; one without a stored end only by the log.
    #[test]
    fn a_sweep_drops_agent_tokens_that_no_longer_work() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("tokens.json");
        let mut t = Tokens::load(&path).unwrap();
        let a = t.issue("demo", "s1", 2_000).unwrap();
        let b = t.issue("demo", "s2", 9_000).unwrap();
        t.sweep_expired(1_999, |_, _| true).unwrap();
        assert!(t.lookup(&a).is_some() && t.lookup(&b).is_some());
        t.sweep_expired(2_000, |_, _| true).unwrap();
        assert!(t.lookup(&a).is_none() && t.lookup(&b).is_some());
        t.sweep_expired(2_000, |repo, s| repo == "demo" && s != "s2")
            .unwrap();
        assert!(t.lookup(&b).is_none());
        let text = std::fs::read_to_string(&path).unwrap();
        assert!(!text.contains("s1") && !text.contains("s2"), "{text}");
    }

    #[test]
    fn a_rotation_replaces_the_token_in_one_write() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("tokens.json");
        let mut t = Tokens::load(&path).unwrap();
        let old = t.issue("demo", "s1", 9_000).unwrap();
        let new = t.rotate(&old).unwrap().unwrap();
        assert!(new.starts_with("lonca_") && !new.starts_with("lonca_h_"));
        assert_ne!(new, old);
        let t2 = Tokens::load(&path).unwrap();
        assert!(t2.lookup(&old).is_none());
        assert_eq!(t2.lookup(&new), t.lookup(&new));
        assert!(t.rotate(&old).unwrap().is_none(), "the old one is gone");
        let h = t.issue_human("ayse", "ab", 9_000).unwrap();
        assert!(t.rotate(&h).unwrap().unwrap().starts_with("lonca_h_"));
        t.revoke_sessions("demo", &["s1".into()]).unwrap();
        assert!(
            t.lookup(&new).is_none(),
            "revocation reaches a rotated token"
        );
    }
}