second-brain-api 0.12.0

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
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
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
use std::collections::BTreeMap;
use std::fs;
use std::future::Future;
use std::io::{self, Read, Write};
use std::os::unix::fs::PermissionsExt;
use std::path::{Component, Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, bail};
use minisign_verify::{PublicKey, Signature};
use semver::Version;

pub const RELEASE_PUBLIC_KEY: &str = "RWR7ibyKrwoxCS3nV49/ndvyqAx4vOpSZSnqaijCMK1VlN1mq36HeQ2u";

/// Nonzero because the systemd unit `sb setup` writes restarts only on failure.
pub const EXIT_FOR_RESTART: i32 = 75;

pub const FIRST_CHECK_DELAY: Duration = Duration::from_secs(10 * 60);
pub const CHECK_INTERVAL: Duration = Duration::from_secs(6 * 60 * 60);
pub const MAX_ASSET_BYTES: usize = 256 * 1024 * 1024;
pub const MAX_SIGNATURE_BYTES: usize = 4096;
const MAX_UNPACKED_BYTES: usize = 1024 * 1024 * 1024;
const HTTP_TIMEOUT: Duration = Duration::from_secs(10 * 60);

const PACKAGES: [&str; 3] = ["second-brain-api", "second-brain-cli", "second-brain-mcp"];
const DAEMON: &str = "second-brain-api";
const STAGING_DIR: &str = ".second-brain-update";
const TARGETS: [(&str, &str, &str); 3] = [
    ("linux", "x86_64", "x86_64-unknown-linux-gnu"),
    ("linux", "aarch64", "aarch64-unknown-linux-gnu"),
    ("macos", "aarch64", "aarch64-apple-darwin"),
];

#[derive(Debug, Clone)]
pub struct Install {
    pub dir: PathBuf,
    pub current: Version,
    pub target: &'static str,
}

#[derive(Debug)]
pub enum Outcome {
    UpToDate {
        latest: Version,
    },
    Installed {
        version: Version,
        replaced: Vec<String>,
    },
    Refused {
        version: Version,
        reason: String,
    },
}

pub fn decide_install(release_build: bool, exe: &Path, os: &str, arch: &str) -> Option<Install> {
    if !release_build {
        return None;
    }
    let (_, _, target) = TARGETS.iter().find(|(o, a, _)| *o == os && *a == arch)?;
    Some(Install {
        dir: exe.parent()?.to_path_buf(),
        current: Version::parse(env!("CARGO_PKG_VERSION")).ok()?,
        target,
    })
}

pub fn this_install() -> Option<Install> {
    let exe = std::env::current_exe().and_then(fs::canonicalize).ok()?;
    decide_install(
        cfg!(feature = "self-update"),
        &exe,
        std::env::consts::OS,
        std::env::consts::ARCH,
    )
}

pub trait ReleaseSource {
    fn latest_tag(&self) -> impl Future<Output = anyhow::Result<String>> + Send;
    fn fetch(
        &self,
        tag: &str,
        asset: &str,
        limit: usize,
    ) -> impl Future<Output = anyhow::Result<Vec<u8>>> + Send;
}

pub struct GitHubReleases {
    owner: String,
    repo: String,
    client: reqwest::Client,
}

impl GitHubReleases {
    pub fn from_repository(repository: &str) -> Option<Self> {
        let path = repository
            .trim_end_matches('/')
            .trim_end_matches(".git")
            .strip_prefix("https://github.com/")?;
        let (owner, repo) = path.split_once('/')?;
        if owner.is_empty() || repo.is_empty() || repo.contains('/') {
            return None;
        }
        let client = reqwest::Client::builder()
            .user_agent(concat!("second-brain/", env!("CARGO_PKG_VERSION")))
            .timeout(HTTP_TIMEOUT)
            .build()
            .ok()?;
        Some(Self {
            owner: owner.to_string(),
            repo: repo.to_string(),
            client,
        })
    }

    pub fn download_url(&self, tag: &str, asset: &str) -> String {
        format!(
            "https://github.com/{}/{}/releases/download/{tag}/{asset}",
            self.owner, self.repo
        )
    }

    fn latest_url(&self) -> String {
        format!(
            "https://api.github.com/repos/{}/{}/releases/latest",
            self.owner, self.repo
        )
    }
}

#[derive(serde::Deserialize)]
struct LatestRelease {
    tag_name: String,
}

impl ReleaseSource for GitHubReleases {
    async fn latest_tag(&self) -> anyhow::Result<String> {
        let latest: LatestRelease = self
            .client
            .get(self.latest_url())
            .header(reqwest::header::ACCEPT, "application/vnd.github+json")
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?;
        Ok(latest.tag_name)
    }

    async fn fetch(&self, tag: &str, asset: &str, limit: usize) -> anyhow::Result<Vec<u8>> {
        let mut response = self
            .client
            .get(self.download_url(tag, asset))
            .send()
            .await?
            .error_for_status()?;
        if response.content_length().is_some_and(|n| n > limit as u64) {
            bail!("{asset} is larger than {limit} bytes");
        }
        let mut body = Vec::new();
        while let Some(chunk) = response.chunk().await? {
            if body.len() + chunk.len() > limit {
                bail!("{asset} is larger than {limit} bytes");
            }
            body.extend_from_slice(&chunk);
        }
        Ok(body)
    }
}

struct SignedArchive {
    package: &'static str,
    name: String,
    bytes: Vec<u8>,
    signature: Vec<u8>,
}

pub fn archive_name(package: &str, target: &str) -> String {
    format!("{package}-{target}.tar.xz")
}

pub fn trusted_comment(version: &Version, archive: &str) -> String {
    format!("second-brain {version} {archive}")
}

pub async fn check_once<S: ReleaseSource>(
    source: &S,
    install: &Install,
    key: &PublicKey,
) -> anyhow::Result<Outcome> {
    let tag = source.latest_tag().await?;
    let version = Version::parse(tag.strip_prefix('v').unwrap_or(&tag))
        .with_context(|| format!("latest release tag {tag:?} is not a version"))?;
    if version <= install.current {
        return Ok(Outcome::UpToDate { latest: version });
    }
    if !is_regular_file(&install.dir.join(DAEMON)) {
        return Ok(Outcome::Refused {
            version,
            reason: format!("{} has no {DAEMON} to replace", install.dir.display()),
        });
    }
    if let Err(e) = probe_writable(&install.dir) {
        return Ok(Outcome::Refused {
            version,
            reason: format!("cannot write to {}: {e}", install.dir.display()),
        });
    }

    let mut archives = Vec::with_capacity(PACKAGES.len());
    for package in PACKAGES {
        let name = archive_name(package, install.target);
        let signature = source
            .fetch(&tag, &format!("{name}.minisig"), MAX_SIGNATURE_BYTES)
            .await?;
        let bytes = source.fetch(&tag, &name, MAX_ASSET_BYTES).await?;
        let archive = SignedArchive {
            package,
            name,
            bytes,
            signature,
        };
        if let Err(reason) = verify(key, &version, &archive) {
            return Ok(Outcome::Refused { version, reason });
        }
        archives.push(archive);
    }

    let install = install.clone();
    tokio::task::spawn_blocking(move || unpack_and_install(&install, version, archives)).await?
}

fn verify(key: &PublicKey, version: &Version, archive: &SignedArchive) -> Result<(), String> {
    let name = &archive.name;
    let text = std::str::from_utf8(&archive.signature)
        .map_err(|_| format!("{name}.minisig is not text"))?;
    let signature =
        Signature::decode(text).map_err(|e| format!("{name}.minisig does not parse: {e}"))?;
    key.verify(&archive.bytes, &signature, false)
        .map_err(|e| format!("{name} fails signature verification: {e}"))?;
    let expected = trusted_comment(version, name);
    let found = signature.trusted_comment();
    if found != expected {
        return Err(format!(
            "{name} is signed with trusted comment {found:?}, expected {expected:?}"
        ));
    }
    Ok(())
}

fn unpack_and_install(
    install: &Install,
    version: Version,
    archives: Vec<SignedArchive>,
) -> anyhow::Result<Outcome> {
    let files = match select_files(install, &archives) {
        Ok(files) => files,
        Err(reason) => return Ok(Outcome::Refused { version, reason }),
    };
    drop(archives);
    swap_in(&install.dir, &files)?;
    Ok(Outcome::Installed {
        version,
        replaced: files.into_keys().collect(),
    })
}

fn select_files(
    install: &Install,
    archives: &[SignedArchive],
) -> Result<BTreeMap<String, Vec<u8>>, String> {
    let mut selected: BTreeMap<String, Vec<u8>> = BTreeMap::new();
    for archive in archives {
        let top = format!("{}-{}", archive.package, install.target);
        let files = unpack(&archive.name, &top, &archive.bytes)?;
        if archive.package == DAEMON && !files.contains_key(DAEMON) {
            return Err(format!("{} has no {DAEMON}", archive.name));
        }
        for (name, data) in files {
            if !is_regular_file(&install.dir.join(&name)) {
                continue;
            }
            match selected.get(&name) {
                Some(existing) if *existing != data => {
                    return Err(format!("{name} differs between archives"));
                }
                Some(_) => {}
                None => {
                    selected.insert(name, data);
                }
            }
        }
    }
    if !selected.contains_key(DAEMON) {
        return Err(format!(
            "{} has no {DAEMON} to replace",
            install.dir.display()
        ));
    }
    Ok(selected)
}

fn probe_writable(dir: &Path) -> io::Result<()> {
    let staging = dir.join(STAGING_DIR);
    match fs::remove_dir_all(&staging) {
        Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
        _ => {}
    }
    fs::create_dir(&staging)?;
    fs::remove_dir(&staging)
}

fn is_regular_file(path: &Path) -> bool {
    fs::symlink_metadata(path).is_ok_and(|m| m.is_file())
}

/// Executable regular files directly under `top`, keyed by file name.
fn unpack(name: &str, top: &str, xz: &[u8]) -> Result<BTreeMap<String, Vec<u8>>, String> {
    let mut tar_bytes = Vec::new();
    lzma_rs::xz_decompress(
        &mut &xz[..],
        &mut Capped {
            inner: &mut tar_bytes,
            left: MAX_UNPACKED_BYTES,
        },
    )
    .map_err(|e| format!("{name} does not decompress: {e}"))?;

    let mut files = BTreeMap::new();
    let mut archive = tar::Archive::new(tar_bytes.as_slice());
    let entries = archive
        .entries()
        .map_err(|e| format!("{name} is not a tar archive: {e}"))?;
    for entry in entries {
        let mut entry = entry.map_err(|e| format!("{name} is not a valid tar archive: {e}"))?;
        let path = entry
            .path()
            .map_err(|e| format!("{name} has an unreadable entry path: {e}"))?
            .into_owned();
        let mut parts = Vec::new();
        for component in path.components() {
            match component {
                Component::Normal(part) => parts.push(part),
                Component::CurDir => {}
                _ => {
                    return Err(format!(
                        "{name} has an entry outside its directory: {}",
                        path.display()
                    ));
                }
            }
        }
        let kind = entry.header().entry_type();
        if kind.is_dir() || kind.is_pax_global_extensions() {
            continue;
        }
        if !kind.is_file() {
            return Err(format!(
                "{name} has a non-regular entry: {}",
                path.display()
            ));
        }
        let [dir, file] = parts.as_slice() else {
            continue;
        };
        let mode = entry
            .header()
            .mode()
            .map_err(|e| format!("{name} has an unreadable entry mode: {e}"))?;
        if *dir != top || mode & 0o111 == 0 {
            continue;
        }
        let file = file
            .to_str()
            .ok_or_else(|| format!("{name} has a non-UTF-8 file name"))?
            .to_string();
        let mut data = Vec::new();
        entry
            .read_to_end(&mut data)
            .map_err(|e| format!("{name} has an unreadable entry {file}: {e}"))?;
        files.insert(file, data);
    }
    Ok(files)
}

struct Capped<'a> {
    inner: &'a mut Vec<u8>,
    left: usize,
}

impl Write for Capped<'_> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        if buf.len() > self.left {
            return Err(io::Error::other(format!(
                "unpacks to more than {MAX_UNPACKED_BYTES} bytes"
            )));
        }
        self.left -= buf.len();
        self.inner.extend_from_slice(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

#[derive(Debug)]
pub struct PartialInstall;

impl std::fmt::Display for PartialInstall {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("self-update left a partial install")
    }
}

enum SwapError {
    RolledBack(io::Error),
    Stuck(anyhow::Error),
}

/// Stages every file next to the install so each replacement is a same-filesystem
/// rename, and restores the originals if any rename fails.
fn swap_in(dir: &Path, files: &BTreeMap<String, Vec<u8>>) -> anyhow::Result<()> {
    let staging = dir.join(STAGING_DIR);
    match fs::remove_dir_all(&staging) {
        Err(e) if e.kind() != io::ErrorKind::NotFound => {
            return Err(e).with_context(|| format!("cannot clear {}", staging.display()));
        }
        _ => {}
    }
    fs::create_dir(&staging).with_context(|| format!("cannot create {}", staging.display()))?;
    match stage_and_swap(dir, &staging, files) {
        Ok(()) => {
            if let Err(e) = fs::remove_dir_all(&staging) {
                tracing::warn!("cannot remove {}: {e}", staging.display());
            }
            Ok(())
        }
        Err(SwapError::RolledBack(e)) => {
            if let Err(cleanup) = fs::remove_dir_all(&staging) {
                tracing::warn!("cannot remove {}: {cleanup}", staging.display());
            }
            Err(e).with_context(|| format!("cannot install into {}", dir.display()))
        }
        Err(SwapError::Stuck(e)) => Err(e.context(PartialInstall)),
    }
}

fn keep_backups(dir: &Path, old: &Path) -> String {
    let kept = dir.join(format!(
        "{STAGING_DIR}-backup-{}",
        chrono::Utc::now().format("%Y%m%dT%H%M%S")
    ));
    match fs::rename(old, &kept) {
        Ok(()) => kept.display().to_string(),
        Err(e) => format!(
            "{}, which the next update deletes because moving them out failed ({e})",
            old.display()
        ),
    }
}

fn stage_and_swap(
    dir: &Path,
    staging: &Path,
    files: &BTreeMap<String, Vec<u8>>,
) -> Result<(), SwapError> {
    let new = staging.join("new");
    let old = staging.join("old");
    stage(&new, &old, files).map_err(SwapError::RolledBack)?;

    let mut swapped: Vec<&str> = Vec::new();
    for name in files.keys() {
        let live = dir.join(name);
        let backup = old.join(name);
        let step = fs::hard_link(&live, &backup)
            .or_else(|_| fs::copy(&live, &backup).map(drop))
            .and_then(|()| fs::rename(new.join(name), &live));
        if let Err(e) = step {
            return Err(match roll_back(dir, &old, &swapped) {
                Ok(()) => SwapError::RolledBack(e),
                Err(rollback) => SwapError::Stuck(anyhow::anyhow!(
                    "cannot install {} ({e}) or restore the previous binaries ({rollback}); they are in {}",
                    live.display(),
                    keep_backups(dir, &old)
                )),
            });
        }
        swapped.push(name);
    }
    if let Err(e) = fs::File::open(dir).and_then(|d| d.sync_all()) {
        tracing::warn!("cannot sync {}: {e}", dir.display());
    }
    Ok(())
}

fn stage(new: &Path, old: &Path, files: &BTreeMap<String, Vec<u8>>) -> io::Result<()> {
    fs::create_dir(new)?;
    fs::create_dir(old)?;
    for (name, data) in files {
        let path = new.join(name);
        let mut file = fs::File::create(&path)?;
        file.write_all(data)?;
        file.sync_all()?;
        fs::set_permissions(&path, fs::Permissions::from_mode(0o755))?;
    }
    Ok(())
}

fn roll_back(dir: &Path, old: &Path, swapped: &[&str]) -> io::Result<()> {
    for name in swapped.iter().rev() {
        fs::rename(old.join(name), dir.join(name))?;
    }
    Ok(())
}

/// Logs the outcome and returns the exit code the daemon must exit with, if any.
pub fn report(outcome: &Outcome) -> Option<i32> {
    match outcome {
        Outcome::Installed { version, replaced } => {
            tracing::info!(
                "installed second-brain {version} ({}); exiting so the service manager restarts the daemon",
                replaced.join(", ")
            );
            Some(EXIT_FOR_RESTART)
        }
        Outcome::Refused { version, reason } => {
            tracing::error!("refusing to install second-brain {version}: {reason}");
            None
        }
        Outcome::UpToDate { latest } => {
            tracing::debug!("self-update: latest release {latest} is not newer");
            None
        }
    }
}

pub fn spawn() {
    let Some(install) = this_install() else {
        tracing::info!("self-update off: not a release build for a published target");
        return;
    };
    let Some(source) = GitHubReleases::from_repository(env!("CARGO_PKG_REPOSITORY")) else {
        tracing::error!(
            "self-update off: cannot use {} as a GitHub release source",
            env!("CARGO_PKG_REPOSITORY")
        );
        return;
    };
    let key = match PublicKey::from_base64(RELEASE_PUBLIC_KEY) {
        Ok(key) => key,
        Err(e) => {
            tracing::error!("self-update off: the release public key does not decode: {e}");
            return;
        }
    };
    tracing::info!(
        "self-update on for {} in {}",
        install.target,
        install.dir.display()
    );
    tokio::spawn(async move {
        tokio::time::sleep(FIRST_CHECK_DELAY).await;
        loop {
            match check_once(&source, &install, &key).await {
                Ok(outcome) => {
                    if let Some(code) = report(&outcome) {
                        std::process::exit(code);
                    }
                }
                Err(e) if e.is::<PartialInstall>() => tracing::error!("{e:#}"),
                Err(e) => tracing::warn!("self-update check failed: {e:#}"),
            }
            tokio::time::sleep(CHECK_INTERVAL).await;
        }
    });
}