Add Store support and unsigned app releases

This commit is contained in:
Tamas Csikel
2026-10-25 14:11:49 +01:00
parent 4975784491
commit d7e9fe4568
157 changed files with 22985 additions and 944 deletions

View File

@@ -1,6 +1,6 @@
[package]
name = "sf-update"
description = "SmartFox package updater: signed shell and app packages from the Gitea package registry"
description = "Fennec OS package updater: signed shell and app packages from the Gitea package registry"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -18,3 +18,6 @@ ed25519-dalek = "2"
base64 = "0.22"
tar = "0.4"
ruzstd = "0.8"
[target.'cfg(unix)'.dependencies]
libc = "0.2"

View File

@@ -0,0 +1,272 @@
//! The app store side of sf-update (docs/store.md): reads what the user wants
//! (store.toml, written by the launcher), asks the sources what they offer
//! (catalog.json) and works out which store apps to install, update or
//! remove. Downloading, checking and unpacking reuse the package store.
use std::collections::BTreeMap;
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result};
use sf_ipc::manifest::{AppManifest, version_cmp};
use sf_ipc::store::{Catalog, CatalogApp, INDEX_FILE, Index, MAX_WANTED, PACKAGE_PREFIX, SourceInfo, Wanted, missing_permissions};
use crate::forge::{self, Repo};
use crate::store::Store;
/// Apps one catalog may list.
const MAX_CATALOG_APPS: usize = 200;
/// A store package to download.
#[derive(Debug, Clone)]
pub struct StoreDownload {
pub id: String,
pub package_url: String,
pub approved: Vec<sf_ipc::Permission>,
pub source: String,
}
/// Reads store.toml. The launcher (user tv) writes it, so it is read
/// carefully: no symlinks, a regular file, a size limit.
pub fn read_wanted(path: &Path) -> Result<Wanted> {
let mut opts = std::fs::OpenOptions::new();
opts.read(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
}
let file = match opts.open(path) {
Ok(f) => f,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Wanted::default()),
Err(e) => return Err(e).with_context(|| format!("opening {}", path.display())),
};
let meta = file.metadata()?;
anyhow::ensure!(meta.is_file(), "{} is not a regular file", path.display());
anyhow::ensure!(meta.len() <= MAX_WANTED, "{} is too large", path.display());
let mut text = String::new();
use std::io::Read;
file.take(MAX_WANTED).read_to_string(&mut text)?;
Wanted::parse(&text)
}
fn now() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
/// The canonical address of a source, or the input if it doesn't parse.
pub fn canonical(source: &str) -> String {
Repo::parse(source).map(|r| r.url()).unwrap_or_else(|_| source.trim().to_string())
}
/// Asks every source what it offers.
pub fn refresh_catalog(wanted: &Wanted) -> Catalog {
let agent = forge::agent();
let mut sources: Vec<String> = Vec::new();
for s in wanted.sources.iter().chain(wanted.apps.values().map(|a| &a.source)) {
let c = canonical(s);
if !sources.contains(&c) {
sources.push(c);
}
}
let mut catalog = Catalog { updated_at: now(), ..Default::default() };
for url in sources {
let mut info = SourceInfo { url: url.clone(), ..Default::default() };
match Repo::parse(&url).and_then(|r| forge::detect(&agent, &r)) {
Err(e) => info.error = Some(format!("{e:#}")),
Ok(repo) => match forge::raw_file(&agent, &repo, INDEX_FILE) {
Ok(Some(text)) => {
info.kind = "catalog".into();
match toml::from_str::<Index>(&text) {
Err(e) => info.error = Some(format!("{INDEX_FILE}: {e}")),
Ok(index) => {
info.name = index.name.clone();
let mut errors = Vec::new();
for app_url in index.apps.iter().take(MAX_CATALOG_APPS) {
match Repo::parse(app_url).and_then(|r| forge::detect(&agent, &r)).and_then(|r| app_entry(&agent, &r)) {
Ok(Some(mut app)) => {
app.catalog = Some(url.clone());
catalog.apps.push(app);
info.apps += 1;
}
Ok(None) => {}
Err(e) => errors.push(format!("{app_url}: {e:#}")),
}
}
for e in &errors {
log::warn!("store: {e}");
}
if info.apps == 0 && !errors.is_empty() {
info.error = errors.into_iter().next();
}
}
}
}
Ok(None) | Err(_) => {
info.kind = "app".into();
match app_entry(&agent, &repo) {
Ok(Some(app)) => {
info.name = app.name.clone();
info.apps = 1;
catalog.apps.push(app);
}
Ok(None) => info.error = Some("no release with an app.toml yet".into()),
Err(e) => info.error = Some(format!("{e:#}")),
}
}
},
}
if let Some(e) = &info.error {
log::warn!("store source {url}: {e}");
}
catalog.sources.push(info);
}
// One entry per id: the source the app is installed from wins, else the first.
let mut seen: BTreeMap<String, usize> = BTreeMap::new();
let mut apps: Vec<CatalogApp> = Vec::new();
for app in catalog.apps.drain(..) {
let pinned = wanted.apps.get(&app.id).map(|w| canonical(&w.source));
match seen.get(&app.id) {
Some(&i) => {
if pinned.as_deref() == Some(app.source.as_str()) && apps[i].source != app.source {
apps[i] = app;
}
}
None => {
seen.insert(app.id.clone(), apps.len());
apps.push(app);
}
}
}
catalog.apps = apps;
catalog
}
/// The newest release of one app repo.
fn app_entry(agent: &ureq::Agent, repo: &Repo) -> Result<Option<CatalogApp>> {
let Some(release) = forge::latest_release(agent, repo)? else { return Ok(None) };
let manifest_asset = release.asset("app.toml").context("app.toml")?;
let app: AppManifest = toml::from_str(&forge::asset_text(agent, manifest_asset)?).context("app.toml")?;
app.check_store_rules()?;
anyhow::ensure!(crate::registry::is_release(&app.version), "version {} is not a release version (1.2.3)", app.version);
let file = format!("{}-{}.tar.zst", app.id, app.version);
let package = release.asset(&file).with_context(|| format!("release {} has no {file}", release.tag))?;
Ok(Some(CatalogApp {
id: app.id.clone(),
name: app.name.clone(),
version: app.version.clone(),
kind: format!("{:?}", app.kind).to_lowercase(),
category: app.category.clone(),
description: app.description.clone(),
author: app.author.clone().unwrap_or_default(),
homepage: app.homepage.clone().unwrap_or_else(|| repo.url()),
license: app.license.clone().unwrap_or_default(),
accent: app.accent.clone(),
permissions: app.permissions(),
source: repo.url(),
catalog: None,
package_url: package.url.clone(),
installed: None,
blocked: None,
}))
}
/// Marks what's installed and what's held back, and returns the store
/// packages to download (new installs and updates).
pub fn plan(store: &Store, wanted: &Wanted, catalog: &mut Catalog) -> BTreeMap<String, (String, StoreDownload)> {
let mut out = BTreeMap::new();
for app in &mut catalog.apps {
let name = format!("{PACKAGE_PREFIX}{}", app.id);
app.installed = store.installed(&name);
app.blocked = None;
let Some(want) = wanted.apps.get(&app.id) else { continue };
if canonical(&want.source) != app.source {
continue;
}
if !missing_permissions(&app.permissions, &want.permissions).is_empty() {
app.blocked = Some("permissions".into());
continue;
}
let newer = app.installed.as_deref().is_none_or(|i| version_cmp(&app.version, i).is_gt());
if newer && !store.bad(&name).contains(&app.version) {
out.insert(
name,
(
app.version.clone(),
StoreDownload {
id: app.id.clone(),
package_url: app.package_url.clone(),
approved: want.permissions.clone(),
source: app.source.clone(),
},
),
);
}
}
out
}
/// Removes store apps the user no longer wants.
pub fn remove_unwanted(store: &Store, wanted: &Wanted) -> bool {
let mut changed = false;
for id in store.store_apps() {
if !wanted.apps.contains_key(&id) {
match store.remove_store_app(&id) {
Ok(()) => changed = true,
Err(e) => log::error!("removing {id}: {e:#}"),
}
}
}
changed
}
pub fn write_catalog(path: &Path, catalog: &Catalog) {
let ok = (|| -> Result<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let tmp = path.with_extension("json.tmp");
std::fs::write(&tmp, serde_json::to_vec_pretty(catalog)?)?;
std::fs::rename(&tmp, path)?;
Ok(())
})();
if let Err(e) = ok {
log::warn!("writing {}: {e:#}", path.display());
}
}
/// Downloads a store package into `dir`.
pub fn download(d: &StoreDownload, version: &str, dir: &Path) -> Result<std::path::PathBuf> {
let agent = forge::agent();
let file = dir.join(format!("{}-{version}.tar.zst", d.id));
let n = forge::download(&agent, &d.package_url, &file, crate::registry::MAX_PACKAGE)?;
log::info!("downloaded {} {version} ({n} bytes)", d.id);
Ok(file)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn canonical_sources() {
assert_eq!(canonical("github.com/Fox/App.git"), "https://github.com/Fox/App");
assert_eq!(canonical(" not a url "), "not a url");
}
#[cfg(unix)]
#[test]
fn wanted_file_is_read_carefully() {
let dir = std::env::temp_dir().join(format!("sf-store-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let real = dir.join("real.toml");
std::fs::write(&real, "sources = ['github.com/a/b']\n").unwrap();
assert_eq!(read_wanted(&real).unwrap().sources, ["github.com/a/b"]);
let link = dir.join("link.toml");
let _ = std::fs::remove_file(&link);
std::os::unix::fs::symlink(&real, &link).unwrap();
assert!(read_wanted(&link).is_err());
assert!(read_wanted(&dir.join("missing.toml")).unwrap().apps.is_empty());
std::fs::remove_dir_all(&dir).unwrap();
}
}

View File

@@ -21,6 +21,7 @@ struct File {
root: Option<PathBuf>,
requests: Option<PathBuf>,
factory: Option<PathBuf>,
store_wanted: Option<PathBuf>,
}
impl File {
@@ -38,6 +39,7 @@ impl File {
root: o.root.or(self.root),
requests: o.requests.or(self.requests),
factory: o.factory.or(self.factory),
store_wanted: o.store_wanted.or(self.store_wanted),
}
}
}
@@ -57,6 +59,10 @@ pub struct Config {
pub requests: PathBuf,
/// Versions of the copies built into the image.
pub factory: PathBuf,
/// What the user wants from the store (written by the launcher).
pub store_wanted: PathBuf,
/// What the store sources offer (written here).
pub catalog: PathBuf,
}
impl Config {
@@ -84,12 +90,15 @@ impl Config {
}
None => None,
};
let root = file.root.unwrap_or_else(|| "/var/lib/sf-pkg".into());
Ok(Config {
catalog: root.join("store").join("catalog.json"),
store_wanted: file.store_wanted.unwrap_or_else(|| sf_ipc::store::WANTED_FILE.into()),
server: server.trim_end_matches('/').to_string(),
owner,
auth,
public_key,
root: file.root.unwrap_or_else(|| "/var/lib/sf-pkg".into()),
root,
requests: file.requests.unwrap_or_else(|| "/var/lib/smartfox/update-requests".into()),
factory: file.factory.unwrap_or_else(|| "/usr/share/smartfox/factory-versions.toml".into()),
})

View File

@@ -0,0 +1,326 @@
//! Store sources: app repos on GitHub, Gitea/Forgejo (Codeberg too) and
//! GitLab. An app is published as a release with two assets (docs/store.md):
//!
//! app.toml the manifest (name, permissions)
//! <id>-<version>.tar.zst the package
//!
//! A catalog repo lists many app repos in `smartfox-store.toml` on its
//! default branch.
//!
//! Requests go without our registry login (it must never reach third-party
//! servers), HTTPS only, with size limits on everything.
use std::io::Read;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use serde::Deserialize;
const MAX_JSON: u64 = 4 * 1024 * 1024;
const MAX_TEXT: u64 = 256 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Forge {
GitHub,
Gitea,
GitLab,
}
/// A repository on a forge.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Repo {
/// None: not known yet (self-hosted), found out by `detect`.
pub forge: Option<Forge>,
/// https://host
pub base: String,
/// owner/repo (GitLab: group/subgroup/project)
pub path: String,
}
impl Repo {
/// What the user typed: `https://github.com/o/r(.git)`, `github.com/o/r`,
/// or with an explicit forge: `gitea:git.example.org/o/r`,
/// `gitlab:gitlab.example.org/group/project`, `github:o/r`.
pub fn parse(input: &str) -> Result<Repo> {
let input = input.trim();
let (forge, rest) = match input.split_once(':') {
Some(("github", r)) => (Some(Forge::GitHub), r),
Some(("gitea" | "forgejo", r)) => (Some(Forge::Gitea), r),
Some(("gitlab", r)) => (Some(Forge::GitLab), r),
_ => (None, input),
};
let rest = rest.trim_start_matches('/');
let rest = if let Some(r) = rest.strip_prefix("https://") {
r
} else if rest.starts_with("http://") {
bail!("only https:// sources are allowed");
} else {
rest
};
let rest = rest.split(['?', '#']).next().unwrap_or("").trim_end_matches('/');
let rest = rest.strip_suffix(".git").unwrap_or(rest);
let (host, path) = match (forge, rest.split_once('/')) {
(Some(Forge::GitHub), Some((h, p))) if !h.contains('.') => ("github.com", format!("{h}/{p}")),
(_, Some((h, p))) => (h, p.to_string()),
_ => bail!("not a repository address: {input}"),
};
let host = host.to_ascii_lowercase();
let valid_host = !host.is_empty() && host.contains('.') && host.bytes().all(|b| b.is_ascii_alphanumeric() || b"-.:".contains(&b));
if !valid_host {
bail!("bad host in {input}");
}
let parts: Vec<&str> = path.split('/').collect();
let valid_part = |p: &&str| !p.is_empty() && *p != "." && *p != ".." && p.bytes().all(|b| b.is_ascii_alphanumeric() || b"-._".contains(&b));
if parts.len() < 2 || !parts.iter().all(valid_part) {
bail!("expected owner/repository in {input}");
}
let forge = forge.or(match host.as_str() {
"github.com" => Some(Forge::GitHub),
"gitlab.com" | "framagit.org" => Some(Forge::GitLab),
"codeberg.org" => Some(Forge::Gitea),
_ => None,
});
if matches!(forge, Some(Forge::GitHub | Forge::Gitea)) && parts.len() != 2 {
bail!("expected owner/repository in {input}");
}
Ok(Repo { forge, base: format!("https://{host}"), path })
}
/// Canonical form, stored in store.toml and catalog.json.
pub fn url(&self) -> String {
format!("{}/{}", self.base, self.path)
}
fn encoded_path(&self) -> String {
self.path.replace('/', "%2F")
}
}
#[derive(Debug, Clone)]
pub struct Asset {
pub name: String,
pub url: String,
}
#[derive(Debug, Clone)]
pub struct Release {
pub tag: String,
pub assets: Vec<Asset>,
}
impl Release {
pub fn asset(&self, name: &str) -> Option<&Asset> {
self.assets.iter().find(|a| a.name == name)
}
}
pub fn agent() -> ureq::Agent {
ureq::Agent::config_builder()
.timeout_connect(Some(Duration::from_secs(15)))
.timeout_recv_response(Some(Duration::from_secs(60)))
.timeout_recv_body(Some(Duration::from_secs(1800)))
.https_only(true)
.user_agent(concat!("FennecOS-store/", env!("CARGO_PKG_VERSION")))
.build()
.into()
}
/// GET returning None on 404.
fn get_text(agent: &ureq::Agent, url: &str, limit: u64) -> Result<Option<String>> {
match agent.get(url).header("Accept", "application/json, text/plain, */*").call() {
Ok(resp) => {
let mut body = String::new();
resp.into_body().into_reader().take(limit + 1).read_to_string(&mut body).with_context(|| format!("reading {url}"))?;
if body.len() as u64 > limit {
bail!("{url}: response is too large");
}
Ok(Some(body))
}
Err(ureq::Error::StatusCode(404)) => Ok(None),
Err(ureq::Error::StatusCode(403 | 429)) if url.contains("api.github.com") => {
bail!("GitHub rate limit reached, try again later")
}
Err(e) => Err(e).with_context(|| format!("GET {url}")),
}
}
/// Works out the forge of a self-hosted repo.
pub fn detect(agent: &ureq::Agent, repo: &Repo) -> Result<Repo> {
if repo.forge.is_some() {
return Ok(repo.clone());
}
let gitea = format!("{}/api/v1/repos/{}", repo.base, repo.path);
if repo.path.matches('/').count() == 1 && get_text(agent, &gitea, MAX_JSON).ok().flatten().is_some() {
return Ok(Repo { forge: Some(Forge::Gitea), ..repo.clone() });
}
let gitlab = format!("{}/api/v4/projects/{}", repo.base, repo.encoded_path());
if get_text(agent, &gitlab, MAX_JSON).ok().flatten().is_some() {
return Ok(Repo { forge: Some(Forge::GitLab), ..repo.clone() });
}
bail!("{}: no public GitHub, Gitea or GitLab repository found", repo.url())
}
#[derive(Deserialize)]
struct GhRelease {
tag_name: String,
#[serde(default)]
draft: bool,
#[serde(default)]
prerelease: bool,
#[serde(default)]
assets: Vec<GhAsset>,
}
#[derive(Deserialize)]
struct GhAsset {
name: String,
browser_download_url: String,
}
#[derive(Deserialize)]
struct GlRelease {
tag_name: String,
#[serde(default)]
upcoming_release: bool,
#[serde(default)]
assets: GlAssets,
}
#[derive(Deserialize, Default)]
struct GlAssets {
#[serde(default)]
links: Vec<GlLink>,
}
#[derive(Deserialize)]
struct GlLink {
name: String,
url: String,
#[serde(default)]
direct_asset_url: Option<String>,
}
/// The newest published (not draft, not pre-release) release that carries
/// an `app.toml`.
pub fn latest_release(agent: &ureq::Agent, repo: &Repo) -> Result<Option<Release>> {
let releases: Vec<Release> = match repo.forge.context("unknown forge")? {
Forge::GitHub => {
let url = format!("https://api.github.com/repos/{}/releases?per_page=20", repo.path);
let Some(text) = get_text(agent, &url, MAX_JSON)? else { return Ok(None) };
let list: Vec<GhRelease> = serde_json::from_str(&text).context("GitHub releases")?;
list.into_iter().filter(|r| !r.draft && !r.prerelease).map(gh_release).collect()
}
Forge::Gitea => {
let url = format!("{}/api/v1/repos/{}/releases?limit=20", repo.base, repo.path);
let Some(text) = get_text(agent, &url, MAX_JSON)? else { return Ok(None) };
let list: Vec<GhRelease> = serde_json::from_str(&text).context("Gitea releases")?;
list.into_iter().filter(|r| !r.draft && !r.prerelease).map(gh_release).collect()
}
Forge::GitLab => {
let url = format!("{}/api/v4/projects/{}/releases?per_page=20", repo.base, repo.encoded_path());
let Some(text) = get_text(agent, &url, MAX_JSON)? else { return Ok(None) };
let list: Vec<GlRelease> = serde_json::from_str(&text).context("GitLab releases")?;
list.into_iter()
.filter(|r| !r.upcoming_release)
.map(|r| Release {
tag: r.tag_name,
assets: r.assets.links.into_iter().map(|l| Asset { url: l.direct_asset_url.unwrap_or(l.url), name: l.name }).collect(),
})
.collect()
}
};
Ok(releases.into_iter().find(|r| r.asset("app.toml").is_some()))
}
fn gh_release(r: GhRelease) -> Release {
Release { tag: r.tag_name, assets: r.assets.into_iter().map(|a| Asset { name: a.name, url: a.browser_download_url }).collect() }
}
/// A file from the default branch (catalogs: `smartfox-store.toml`).
pub fn raw_file(agent: &ureq::Agent, repo: &Repo, file: &str) -> Result<Option<String>> {
let url = match repo.forge.context("unknown forge")? {
Forge::GitHub => format!("https://raw.githubusercontent.com/{}/HEAD/{file}", repo.path),
Forge::Gitea => format!("{}/api/v1/repos/{}/raw/{file}", repo.base, repo.path),
Forge::GitLab => format!("{}/api/v4/projects/{}/repository/files/{}/raw?ref=HEAD", repo.base, repo.encoded_path(), file.replace('/', "%2F")),
};
get_text(agent, &url, MAX_TEXT)
}
/// A small text asset (the release's app.toml).
pub fn asset_text(agent: &ureq::Agent, asset: &Asset) -> Result<String> {
get_text(agent, &asset.url, MAX_TEXT)?.with_context(|| format!("{} is missing", asset.name))
}
/// Downloads an asset into `path`, at most `limit` bytes.
pub fn download(agent: &ureq::Agent, url: &str, path: &std::path::Path, limit: u64) -> Result<u64> {
let resp = agent.get(url).call().with_context(|| format!("GET {url}"))?;
let mut out = std::fs::File::create(path).with_context(|| format!("creating {}", path.display()))?;
let mut body = resp.into_body().into_reader().take(limit + 1);
let n = std::io::copy(&mut body, &mut out).with_context(|| format!("downloading {url}"))?;
if n > limit {
bail!("{url} is larger than {limit} bytes");
}
out.sync_all()?;
Ok(n)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_repo_addresses() {
let r = Repo::parse("https://github.com/Fox/hello-app.git").unwrap();
assert_eq!((r.forge, r.url()), (Some(Forge::GitHub), "https://github.com/Fox/hello-app".to_string()));
assert_eq!(Repo::parse("github.com/fox/x/").unwrap().url(), "https://github.com/fox/x");
assert_eq!(Repo::parse("github:fox/x").unwrap().url(), "https://github.com/fox/x");
let r = Repo::parse("gitlab.com/group/sub/proj").unwrap();
assert_eq!((r.forge, r.path.as_str()), (Some(Forge::GitLab), "group/sub/proj"));
let r = Repo::parse("gitea:git.example.org/o/r").unwrap();
assert_eq!((r.forge, r.base.as_str()), (Some(Forge::Gitea), "https://git.example.org"));
let r = Repo::parse("https://gitea.bluefox.support/bluefox/store").unwrap();
assert_eq!(r.forge, None);
assert!(Repo::parse("http://github.com/a/b").is_err());
assert!(Repo::parse("github.com/a").is_err());
assert!(Repo::parse("github.com/a/b/c").is_err());
assert!(Repo::parse("github.com/../b").is_err());
assert!(Repo::parse("exa mple.org/a/b").is_err());
}
#[test]
fn parses_releases() {
let gh: Vec<GhRelease> = serde_json::from_str(
r#"[{"tag_name":"v2","draft":true,"assets":[]},{"tag_name":"v1","prerelease":false,"assets":[{"name":"app.toml","browser_download_url":"https://x/app.toml","size":3}]}]"#,
)
.unwrap();
let rel: Vec<Release> = gh.into_iter().filter(|r| !r.draft).map(gh_release).collect();
assert_eq!(rel[0].tag, "v1");
assert_eq!(rel[0].asset("app.toml").unwrap().url, "https://x/app.toml");
let gl: Vec<GlRelease> = serde_json::from_str(r#"[{"tag_name":"1.0","assets":{"links":[{"name":"app.toml","url":"https://a","direct_asset_url":"https://b"}]}}]"#).unwrap();
assert_eq!(gl[0].assets.links[0].direct_asset_url.as_deref(), Some("https://b"));
}
}
/// Talks to the real forges: `cargo test -p sf-update -- --ignored live`.
#[cfg(test)]
mod live {
use super::*;
#[test]
#[ignore]
fn live_forges() {
let agent = agent();
for (url, file) in [
("github.com/BurntSushi/ripgrep", "README.md"),
("codeberg.org/forgejo/forgejo", "README.md"),
("gitlab.com/gitlab-org/cli", "README.md"),
("gitea:gitea.com/gitea/tea", "README.md"),
] {
let repo = detect(&agent, &Repo::parse(url).unwrap()).unwrap();
let release = latest_release(&agent, &repo).unwrap();
let readme = raw_file(&agent, &repo, file).unwrap();
println!("{url}: {:?}, release with app.toml: {}, readme: {} bytes", repo.forge, release.is_some(), readme.map(|r| r.len()).unwrap_or(0));
assert!(raw_file(&agent, &repo, "no-such-file.toml").unwrap().is_none());
}
}
}

View File

@@ -1,27 +1,32 @@
//! sf-update: installs signed SmartFox packages (the shell and the apps) from
//! the Gitea package registry onto the writable data partition. The root
//! file system stays read-only and keeps the factory copies as a fallback.
//! sf-update: installs signed Fennec OS packages (the shell and the apps) from
//! the Gitea package registry, and store apps from their own GitHub, Gitea or
//! GitLab repos, onto the writable data partition. The root file system stays
//! read-only and keeps the factory copies as a fallback.
//!
//! Protocol and layout: docs/updates.md.
//! Protocol and layout: docs/updates.md, docs/store.md.
//!
//! sf-update check ask the server what's new (status.json)
//! sf-update check ask the servers what's new (status.json, catalog.json)
//! sf-update auto check, then download and stage what's new (timer)
//! sf-update apply switch staged packages live (at boot)
//! sf-update install check, download, apply now and restart the UI
//! sf-update store install / remove store apps as store.toml says, now
//! sf-update requests handle the launcher's request files (path unit)
//! sf-update status print status.json
mod appstore;
mod config;
mod forge;
mod registry;
mod store;
use std::collections::BTreeMap;
use std::path::Path;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use crate::config::Config;
use crate::store::Store;
use crate::store::{Expect, Store};
fn main() {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
@@ -34,14 +39,14 @@ fn main() {
fn run(cmd: &str) -> Result<()> {
let cfg = Config::load()?;
let store = Store::open(&cfg)?;
let store = Store::open(&cfg.root, &cfg.factory)?;
match cmd {
"status" => {
println!("{}", serde_json::to_string_pretty(&store.read_status())?);
return Ok(());
}
"check" | "auto" | "apply" | "install" | "requests" => {}
_ => bail!("usage: sf-update check|auto|apply|install|requests|status"),
"check" | "auto" | "apply" | "install" | "store" | "requests" => {}
_ => bail!("usage: sf-update check|auto|apply|install|store|requests|status"),
}
// One run at a time (timer, boot and launcher requests can overlap).
let _lock = store.lock(Duration::from_secs(600))?;
@@ -50,28 +55,78 @@ fn run(cmd: &str) -> Result<()> {
"auto" => auto(&cfg, &store),
"apply" => apply(&store).map(drop),
"install" => install(&cfg, &store),
"store" => store_sync(&cfg, &store),
"requests" => requests(&cfg, &store),
_ => unreachable!(),
}
}
/// Asks the registry for the newest version of every package and records
/// which ones are newer than what's installed.
fn check(cfg: &Config, store: &Store) -> Result<Vec<store::Pending>> {
store.set_state("checking", "");
let latest = match registry::latest_versions(cfg) {
Ok(l) => l,
/// The store's plan: newest versions of the wanted store apps that may be
/// installed, with where to get them. None if store.toml can't be read
/// (then nothing is installed or removed).
fn store_plan(cfg: &Config, store: &Store) -> Option<(sf_ipc::store::Wanted, BTreeMap<String, (String, appstore::StoreDownload)>)> {
let wanted = match appstore::read_wanted(&cfg.store_wanted) {
Ok(w) => w,
Err(e) => {
store.set_state("error", &format!("{e:#}"));
return Err(e);
log::error!("store: {e:#}");
return None;
}
};
let pending = store.refresh(&latest);
if wanted.sources.is_empty() && wanted.apps.is_empty() {
appstore::write_catalog(&cfg.catalog, &Default::default());
return Some((wanted, BTreeMap::new()));
}
let mut catalog = appstore::refresh_catalog(&wanted);
let plan = appstore::plan(store, &wanted, &mut catalog);
appstore::write_catalog(&cfg.catalog, &catalog);
Some((wanted, plan))
}
/// Asks the registry and the store sources for the newest version of every
/// package and records which ones are newer than what's installed.
fn check(cfg: &Config, store: &Store) -> Result<Vec<store::Pending>> {
store.set_state("checking", "");
let official = registry::latest_versions(cfg);
let mut latest = official.as_ref().cloned().unwrap_or_default();
let mut downloads = BTreeMap::new();
if let Some((_, plan)) = store_plan(cfg, store) {
for (name, (version, d)) in plan {
latest.insert(name.clone(), version);
downloads.insert(name, d);
}
}
let mut pending = store.refresh(&latest);
for p in &mut pending {
p.store = downloads.remove(&p.name);
}
// A store app without download info (shouldn't happen) is skipped.
pending.retain(|p| registry::store_id(&p.name).is_none() || p.store.is_some());
if let Err(e) = official {
store.set_state("error", &format!("{e:#}"));
return Err(e);
}
store.set_state("idle", "");
log::info!("{} update(s) available", pending.len());
Ok(pending)
}
/// Downloads, checks and stages one package.
fn fetch(cfg: &Config, store: &Store, p: &store::Pending) -> Result<()> {
let dir = store.download_dir()?;
match &p.store {
None => {
let (pkg, sig) = registry::download(cfg, &p.name, &p.version, &dir)?;
store.verify_and_unpack(&cfg.public_key, &p.name, &p.version, &pkg, &sig, &Expect::Official)?;
}
Some(d) => {
let pkg = appstore::download(d, &p.version, &dir)?;
let expect = Expect::Store { id: &d.id, approved: &d.approved, source: &d.source };
store.unpack_store(&p.name, &p.version, &pkg, &expect)?;
}
}
store.stage(&p.name, &p.version)
}
/// Downloads and stages each pending package. Failures of one package don't
/// stop the others; the first error is reported.
fn download(cfg: &Config, store: &Store, pending: &[store::Pending]) -> Result<usize> {
@@ -83,12 +138,7 @@ fn download(cfg: &Config, store: &Store, pending: &[store::Pending]) -> Result<u
continue;
}
store.set_state("downloading", &format!("{} {}", p.name, p.version));
let result = (|| -> Result<()> {
let dir = store.download_dir()?;
let (pkg, sig) = registry::download(cfg, &p.name, &p.version, &dir)?;
store.verify_and_unpack(cfg, &p.name, &p.version, &pkg, &sig)?;
store.stage(&p.name, &p.version)
})();
let result = fetch(cfg, store, p);
let _ = std::fs::remove_dir_all(store.download_dir_path());
match result {
Ok(()) => {
@@ -123,7 +173,7 @@ fn auto(cfg: &Config, store: &Store) -> Result<()> {
/// Switches staged packages live. Returns which kinds changed.
fn apply(store: &Store) -> Result<store::Applied> {
let applied = store.apply_staged()?;
let applied = store.apply_staged(|_| true)?;
store.gc();
store.write_status(|_| {});
Ok(applied)
@@ -139,13 +189,45 @@ fn install(cfg: &Config, store: &Store) -> Result<()> {
result.map(drop)
}
/// The store screen changed store.toml: install new apps and approved
/// updates, remove the ones the user uninstalled, all right away. The
/// launcher picks the new app list up by itself; nothing restarts.
fn store_sync(cfg: &Config, store: &Store) -> Result<()> {
store.set_state("checking", "");
let Some((wanted, plan)) = store_plan(cfg, store) else {
store.set_state("error", "store.toml can't be read");
bail!("store.toml can't be read");
};
appstore::remove_unwanted(store, &wanted);
let pending: Vec<store::Pending> = plan
.into_iter()
.map(|(name, (version, d))| store::Pending { name, version, store: Some(d) })
.collect();
let result = download(cfg, store, &pending);
store.apply_staged(|name| registry::store_id(name).is_some())?;
store.link_apps()?;
store.gc();
// The catalog's "installed" marks are now stale; refresh them from disk.
if let Some(mut catalog) = sf_ipc::store::Catalog::load(&cfg.catalog) {
for app in &mut catalog.apps {
app.installed = store.installed(&format!("{}{}", sf_ipc::store::PACKAGE_PREFIX, app.id));
}
appstore::write_catalog(&cfg.catalog, &catalog);
}
store.write_status(|_| {});
if result.is_ok() {
store.set_state("idle", "");
}
result.map(drop)
}
/// Restarts what an update touched: the remote driver for a new shell, the
/// TV session (cage + launcher) for a new shell or new apps.
fn restart(applied: &store::Applied) {
if applied.shell {
systemctl(&["restart", "sf-remote.service"]);
}
if applied.shell || applied.apps {
if applied.shell || applied.apps || applied.store {
restart_ui();
}
}
@@ -164,9 +246,10 @@ fn systemctl(args: &[&str]) {
/// The launcher (user tv) can't run anything as root; it drops empty files
/// named after a request into the requests folder, sf-update-requests.path
/// starts this. Only the file names are used, never their contents.
/// starts this. Only the file names are used, never their contents (the
/// store request reads store.toml, carefully).
fn requests(cfg: &Config, store: &Store) -> Result<()> {
const ORDER: [&str; 4] = ["rollback", "confirm", "install", "check"];
const ORDER: [&str; 5] = ["rollback", "confirm", "store", "install", "check"];
let dir = &cfg.requests;
let mut result = Ok(());
for _ in 0..10 {
@@ -178,6 +261,7 @@ fn requests(cfg: &Config, store: &Store) -> Result<()> {
let r = match name {
"rollback" => rollback(store),
"confirm" => store.confirm_shell(),
"store" => store_sync(cfg, store),
"install" => install(cfg, store),
_ => check(cfg, store).map(drop),
};
@@ -213,4 +297,3 @@ fn rollback(store: &Store) -> Result<()> {
}
Ok(())
}

View File

@@ -14,18 +14,29 @@ use serde::Deserialize;
use sf_ipc::manifest::version_cmp;
/// Largest package we'll download.
const MAX_PACKAGE: u64 = 1024 * 1024 * 1024;
pub const MAX_PACKAGE: u64 = 1024 * 1024 * 1024;
use crate::config::Config;
/// Package names this updater handles.
pub fn is_ours(name: &str) -> bool {
/// Official package names (from our registry).
pub fn is_official(name: &str) -> bool {
name == "sf-shell" || name.strip_prefix("sf-app-").is_some_and(|id| !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'))
}
/// Release versions only: digits and dots (prereleases like 1.2.0-rc1 are skipped).
/// Store app id of a package name (`store-<id>`).
pub fn store_id(name: &str) -> Option<&str> {
name.strip_prefix(sf_ipc::store::PACKAGE_PREFIX).filter(|id| sf_ipc::manifest::is_store_id(id))
}
/// Package names this updater handles: official ones and store apps.
pub fn is_ours(name: &str) -> bool {
is_official(name) || store_id(name).is_some()
}
/// Release versions only: digits and dots, up to four parts (prereleases
/// like 1.2.0-rc1 are skipped).
pub fn is_release(version: &str) -> bool {
!version.is_empty() && version.split('.').all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) && version.split('.').count() <= 3
!version.is_empty() && version.split('.').all(|p| !p.is_empty() && p.len() <= 9 && p.bytes().all(|b| b.is_ascii_digit())) && version.split('.').count() <= 4
}
fn agent() -> ureq::Agent {
@@ -69,7 +80,7 @@ pub fn latest_versions(cfg: &Config) -> Result<BTreeMap<String, String>> {
break;
}
for p in list {
if !is_ours(&p.name) || !is_release(&p.version) {
if !is_official(&p.name) || !is_release(&p.version) {
continue;
}
match latest.get(&p.name) {
@@ -90,7 +101,7 @@ pub fn file_name(name: &str, version: &str) -> String {
/// Downloads a package and its signature into `dir`.
pub fn download(cfg: &Config, name: &str, version: &str, dir: &Path) -> Result<(PathBuf, Vec<u8>)> {
if !is_ours(name) || !is_release(version) {
if !is_official(name) || !is_release(version) {
bail!("refusing package {name} {version}");
}
let agent = agent();
@@ -124,7 +135,13 @@ mod tests {
assert!(!is_ours("sf-app-"));
assert!(!is_ours("sf-app-../x"));
assert!(!is_ours("other"));
assert!(is_ours("store-io.github.fox.hello"));
assert!(!is_official("store-io.github.fox.hello"));
assert!(!is_ours("store-youtube"));
assert!(!is_ours("store-io.x/../y"));
assert!(is_release("1.2.3"));
assert!(is_release("1.0.0.87"));
assert!(!is_release("1.0.0.0.1"));
assert!(!is_release("1.2.3-rc1"));
assert!(!is_release("1..2"));
assert!(!is_release("../1"));

View File

@@ -7,6 +7,9 @@
//! <name>/bad versions that failed, never installed again
//! sf-shell/trial a new shell that hasn't confirmed a good start yet
//! apps/<id> -> ../sf-app-<id>/current (the launcher reads this folder)
//! store-<id>/ a store app (docs/store.md), same layout plus:
//! source the repo it was installed from
//! store/apps/<id> -> ../../store-<id>/current
//! status.json for the launcher's Updates row
use std::collections::{BTreeMap, BTreeSet};
@@ -17,9 +20,9 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result, bail};
use ed25519_dalek::{Signature, VerifyingKey};
use serde::{Deserialize, Serialize};
use sf_ipc::manifest::version_cmp;
use sf_ipc::Permission;
use sf_ipc::manifest::{AppManifest, version_cmp};
use crate::config::Config;
use crate::registry;
pub const SHELL: &str = "sf-shell";
@@ -50,14 +53,30 @@ pub struct PackageStatus {
pub struct Pending {
pub name: String,
pub version: String,
/// Store apps: where to get it and what it must be.
pub store: Option<crate::appstore::StoreDownload>,
}
#[derive(Debug, Default)]
pub struct Applied {
pub shell: bool,
pub apps: bool,
pub store: bool,
}
/// What a package must be to be installed.
pub enum Expect<'a> {
/// Ours: signed with the Fennec OS key.
Official,
/// A store app: its manifest must follow the store rules and stay within
/// the approved permissions.
Store { id: &'a str, approved: &'a [Permission], source: &'a str },
}
/// Largest unpacked store package and file count.
const MAX_STORE_UNPACKED: u64 = 8 * 1024 * 1024 * 1024;
const MAX_STORE_FILES: usize = 200_000;
#[derive(Deserialize)]
struct PkgInfo {
name: String,
@@ -83,13 +102,18 @@ pub struct Store {
pub struct Lock(#[allow(dead_code)] fs::File);
impl Store {
pub fn open(cfg: &Config) -> Result<Self> {
fs::create_dir_all(&cfg.root).with_context(|| format!("creating {}", cfg.root.display()))?;
let factory = match fs::read_to_string(&cfg.factory) {
Ok(t) => toml::from_str(&t).with_context(|| format!("parsing {}", cfg.factory.display()))?,
pub fn open(root: &Path, factory: &Path) -> Result<Self> {
fs::create_dir_all(root).with_context(|| format!("creating {}", root.display()))?;
let factory = match fs::read_to_string(factory) {
Ok(t) => toml::from_str(&t).with_context(|| format!("parsing {}", factory.display()))?,
Err(_) => BTreeMap::new(),
};
Ok(Store { root: cfg.root.clone(), factory })
Ok(Store { root: root.to_path_buf(), factory })
}
/// Store app folders: `store/` under the root.
pub fn store_dir(&self) -> PathBuf {
self.root.join("store")
}
pub fn lock(&self, wait: Duration) -> Result<Lock> {
@@ -134,7 +158,7 @@ impl Store {
}
/// The version running now: installed package or factory copy, the newer one.
fn installed(&self, name: &str) -> Option<String> {
pub fn installed(&self, name: &str) -> Option<String> {
let current = self.link(name, "current");
let factory = self.factory.get(name).cloned();
match (current, factory) {
@@ -143,7 +167,7 @@ impl Store {
}
}
fn bad(&self, name: &str) -> BTreeSet<String> {
pub fn bad(&self, name: &str) -> BTreeSet<String> {
fs::read_to_string(self.dir(name).join("bad")).unwrap_or_default().lines().map(str::to_string).collect()
}
@@ -164,7 +188,7 @@ impl Store {
let Some(v) = latest.get(&name) else { continue };
let newer = self.installed(&name).is_none_or(|i| version_cmp(v, &i).is_gt());
if newer && !self.bad(&name).contains(v) {
pending.push(Pending { name: name.clone(), version: v.clone() });
pending.push(Pending { name: name.clone(), version: v.clone(), store: None });
}
}
let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
@@ -190,13 +214,24 @@ impl Store {
Ok(d)
}
/// Checks the signature and unpacks into `<name>/<version>/`.
pub fn verify_and_unpack(&self, cfg: &Config, name: &str, version: &str, pkg: &Path, sig: &[u8]) -> Result<()> {
/// Checks the signature with `key` and unpacks into `<name>/<version>/`.
pub fn verify_and_unpack(&self, key: &[u8; 32], name: &str, version: &str, pkg: &Path, sig: &[u8], expect: &Expect) -> Result<()> {
anyhow::ensure!(matches!(expect, Expect::Official), "signed install is for official packages");
let data = fs::read(pkg)?;
let key = VerifyingKey::from_bytes(&cfg.public_key).context("public key")?;
let key = VerifyingKey::from_bytes(key).context("public key")?;
let sig = Signature::from_slice(sig).context("signature: not 64 bytes")?;
key.verify_strict(&data, &sig).context("bad signature")?;
self.unpack(name, version, &data, expect)
}
/// Store packages come from the selected source and need no signature.
pub fn unpack_store(&self, name: &str, version: &str, pkg: &Path, expect: &Expect) -> Result<()> {
anyhow::ensure!(matches!(expect, Expect::Store { .. }), "unsigned install is for store apps");
let data = fs::read(pkg)?;
self.unpack(name, version, &data, expect)
}
fn unpack(&self, name: &str, version: &str, data: &[u8], expect: &Expect) -> Result<()> {
let dir = self.dir(name);
fs::create_dir_all(&dir)?;
let dest = dir.join(version);
@@ -209,18 +244,60 @@ impl Store {
let tmp = dir.join(format!(".tmp-{version}"));
let _ = fs::remove_dir_all(&tmp);
fs::create_dir_all(&tmp)?;
let decoder = ruzstd::decoding::StreamingDecoder::new(&data[..]).map_err(|e| anyhow::anyhow!("zstd: {e}"))?;
let mut archive = tar::Archive::new(decoder);
archive.set_preserve_permissions(true);
archive.set_preserve_ownerships(false);
archive.unpack(&tmp).context("unpacking")?;
let info: PkgInfo = toml::from_str(&fs::read_to_string(tmp.join("pkg.toml")).context("pkg.toml missing")?).context("pkg.toml")?;
if info.name != name || info.version != version {
let result = (|| -> Result<()> {
let decoder = ruzstd::decoding::StreamingDecoder::new(&data[..]).map_err(|e| anyhow::anyhow!("zstd: {e}"))?;
let mut archive = tar::Archive::new(decoder);
archive.set_preserve_ownerships(false);
match expect {
Expect::Official => {
archive.set_preserve_permissions(true);
archive.unpack(&tmp).context("unpacking")?;
}
Expect::Store { .. } => unpack_untrusted(&mut archive, &tmp)?,
}
let info: PkgInfo = toml::from_str(&fs::read_to_string(tmp.join("pkg.toml")).context("pkg.toml missing")?).context("pkg.toml")?;
let expected_name = match expect {
Expect::Official => name,
Expect::Store { id, .. } => id,
};
if info.name != expected_name || info.version != version {
bail!("package says it is {} {}, expected {expected_name} {version}", info.name, info.version);
}
if let Expect::Store { id, approved, .. } = expect {
check_store_manifest(&tmp, id, version, approved)?;
}
Ok(())
})();
if let Err(e) = result {
let _ = fs::remove_dir_all(&tmp);
bail!("package says it is {} {}, expected {name} {version}", info.name, info.version);
return Err(e);
}
fs::rename(&tmp, &dest)?;
if let Expect::Store { source, .. } = expect {
fs::write(dir.join("source"), format!("{source}\n"))?;
}
Ok(())
}
/// Ids of the store apps on disk.
pub fn store_apps(&self) -> Vec<String> {
let Ok(entries) = fs::read_dir(&self.root) else { return Vec::new() };
entries
.flatten()
.filter_map(|e| e.file_name().into_string().ok())
.filter_map(|n| registry::store_id(&n).map(str::to_string))
.collect()
}
/// Uninstalls a store app (its files; the user's data stays in their home).
pub fn remove_store_app(&self, id: &str) -> Result<()> {
let name = format!("{}{id}", sf_ipc::store::PACKAGE_PREFIX);
anyhow::ensure!(registry::store_id(&name).is_some(), "bad store app id {id}");
let _ = fs::remove_file(self.store_dir().join("apps").join(id));
if self.dir(&name).exists() {
fs::remove_dir_all(self.dir(&name)).with_context(|| format!("removing {name}"))?;
log::info!("removed store app {id}");
}
Ok(())
}
@@ -228,12 +305,12 @@ impl Store {
self.set_link(name, "staged", version)
}
/// Makes every staged package live.
pub fn apply_staged(&self) -> Result<Applied> {
/// Makes every staged package live for which `which(name)` says so.
pub fn apply_staged(&self, which: impl Fn(&str) -> bool) -> Result<Applied> {
let mut applied = Applied::default();
let Ok(entries) = fs::read_dir(&self.root) else { return Ok(applied) };
for e in entries.flatten() {
let Some(name) = e.file_name().into_string().ok().filter(|n| registry::is_ours(n)) else { continue };
let Some(name) = e.file_name().into_string().ok().filter(|n| registry::is_ours(n) && which(n)) else { continue };
let Some(v) = self.staged(&name) else { continue };
if self.link(&name, "current").as_deref() != Some(v.as_str()) {
if let Some(cur) = self.link(&name, "current") {
@@ -244,6 +321,8 @@ impl Store {
if name == SHELL {
fs::write(self.dir(&name).join("trial"), &v)?;
applied.shell = true;
} else if registry::store_id(&name).is_some() {
applied.store = true;
} else {
applied.apps = true;
}
@@ -254,17 +333,33 @@ impl Store {
Ok(applied)
}
/// apps/<id> -> ../sf-app-<id>/current for every installed app.
fn link_apps(&self) -> Result<()> {
/// apps/<id> -> ../sf-app-<id>/current for every installed app, and
/// store/apps/<id> -> ../../store-<id>/current for store apps.
pub fn link_apps(&self) -> Result<()> {
let apps = self.root.join("apps");
let store_apps = self.store_dir().join("apps");
fs::create_dir_all(&apps)?;
fs::create_dir_all(&store_apps)?;
let Ok(entries) = fs::read_dir(&self.root) else { return Ok(()) };
for e in entries.flatten() {
let Some(name) = e.file_name().into_string().ok() else { continue };
let Some(id) = name.strip_prefix("sf-app-").filter(|_| registry::is_ours(&name)) else { continue };
let link = apps.join(id);
let (link, target) = if let Some(id) = name.strip_prefix("sf-app-").filter(|_| registry::is_official(&name)) {
(apps.join(id), format!("../{name}/current"))
} else if let Some(id) = registry::store_id(&name) {
(store_apps.join(id), format!("../../{name}/current"))
} else {
continue;
};
if self.link(&name, "current").is_some() && fs::symlink_metadata(&link).is_err() {
symlink(format!("../{name}/current"), &link)?;
symlink(target, &link)?;
}
}
// Links of removed store apps.
if let Ok(entries) = fs::read_dir(&store_apps) {
for e in entries.flatten() {
if !e.path().join("app.toml").exists() {
let _ = fs::remove_file(e.path());
}
}
}
Ok(())
@@ -362,3 +457,213 @@ impl Store {
});
}
}
/// Unpacks a package from a third party: only plain files, folders and
/// symlinks that stay inside, no setuid/setgid bits, nothing writable by
/// others, within size limits.
fn unpack_untrusted<R: std::io::Read>(archive: &mut tar::Archive<R>, dest: &Path) -> Result<()> {
use std::path::Component;
archive.set_preserve_permissions(false);
let mut total = 0u64;
let mut files = 0usize;
for entry in archive.entries().context("reading the package")? {
let mut entry = entry.context("reading the package")?;
let path = entry.path().context("bad path")?.into_owned();
if !path.components().all(|c| matches!(c, Component::Normal(_) | Component::CurDir)) {
bail!("package path {} leaves the package", path.display());
}
match entry.header().entry_type() {
tar::EntryType::Regular | tar::EntryType::Directory => {}
tar::EntryType::Symlink => {
let target = entry.link_name().ok().flatten().context("symlink without target")?;
// Depth of the folder the link is in; ".." may not climb above the package.
let mut level = path.components().filter(|c| matches!(c, Component::Normal(_))).count() as i64 - 1;
for c in target.components() {
match c {
Component::Normal(_) => level += 1,
Component::ParentDir => level -= 1,
Component::CurDir => {}
_ => bail!("symlink {} points outside the package", path.display()),
}
if level < 0 {
bail!("symlink {} points outside the package", path.display());
}
}
}
other => bail!("{}: {other:?} entries are not allowed", path.display()),
}
total += entry.header().size().unwrap_or(0);
files += 1;
if total > MAX_STORE_UNPACKED || files > MAX_STORE_FILES {
bail!("the package is too large");
}
if !entry.unpack_in(dest).with_context(|| format!("unpacking {}", path.display()))? {
bail!("package path {} leaves the package", path.display());
}
}
strip_modes(dest)
}
/// No setuid/setgid/sticky and no group/other write anywhere in `dir`.
#[cfg(unix)]
fn strip_modes(dir: &Path) -> Result<()> {
use std::os::unix::fs::PermissionsExt;
for e in fs::read_dir(dir)?.flatten() {
let meta = fs::symlink_metadata(e.path())?;
if meta.file_type().is_symlink() {
continue;
}
let mode = meta.permissions().mode() & 0o755;
fs::set_permissions(e.path(), fs::Permissions::from_mode(mode))?;
if meta.is_dir() {
strip_modes(&e.path())?;
}
}
Ok(())
}
#[cfg(not(unix))]
fn strip_modes(_dir: &Path) -> Result<()> {
Ok(())
}
/// The manifest inside a store package must match what was offered.
fn check_store_manifest(dir: &Path, id: &str, version: &str, approved: &[Permission]) -> Result<()> {
let text = fs::read_to_string(dir.join("app.toml")).context("app.toml missing")?;
let app: AppManifest = toml::from_str(&text).context("app.toml")?;
anyhow::ensure!(app.id == id, "app.toml says id {}, expected {id}", app.id);
anyhow::ensure!(app.version == version, "app.toml says version {}, expected {version}", app.version);
app.check_store_rules()?;
let missing = sf_ipc::store::missing_permissions(&app.permissions(), approved);
anyhow::ensure!(missing.is_empty(), "the package asks for permissions that were not approved: {missing:?}");
Ok(())
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
const ID: &str = "io.github.fox.hello";
struct Pkg {
tar: tar::Builder<Vec<u8>>,
}
impl Pkg {
fn new(version: &str, perms: &str) -> Pkg {
let mut p = Pkg { tar: tar::Builder::new(Vec::new()) };
p.file("pkg.toml", &format!("name = \"{ID}\"\nversion = \"{version}\"\n"), 0o644);
p.file(
"app.toml",
&format!("id = \"{ID}\"\nname = \"Hello\"\nversion = \"{version}\"\nkind = \"exec\"\nexec = [\"bin/hello\"]\n[sandbox]\npermissions = [{perms}]\n"),
0o644,
);
p.file("bin/hello", "#!/bin/sh\n", 0o755);
p
}
fn file(&mut self, path: &str, body: &str, mode: u32) {
let mut h = tar::Header::new_gnu();
h.set_size(body.len() as u64);
h.set_mode(mode);
self.tar.append_data(&mut h, path, body.as_bytes()).unwrap();
}
fn link(&mut self, path: &str, target: &str) {
let mut h = tar::Header::new_gnu();
h.set_entry_type(tar::EntryType::Symlink);
h.set_size(0);
self.tar.append_link(&mut h, path, target).unwrap();
}
fn write(self, dir: &Path) -> PathBuf {
let tar = self.tar.into_inner().unwrap();
let zst = ruzstd::encoding::compress_to_vec(&tar[..], ruzstd::encoding::CompressionLevel::Fastest);
let path = dir.join("pkg.tar.zst");
fs::write(&path, &zst).unwrap();
path
}
}
fn setup(name: &str) -> (PathBuf, Store) {
let root = std::env::temp_dir().join(format!("sf-update-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let store = Store::open(&root, &root.join("none.toml")).unwrap();
(root, store)
}
#[test]
fn installs_a_store_app_and_refuses_bad_ones() {
let (root, store) = setup("store");
let name = format!("store-{ID}");
let approved = [Permission::Network];
let expect = Expect::Store { id: ID, approved: &approved, source: "https://github.com/fox/hello" };
// A good package, with a setuid bit that must be stripped.
let mut p = Pkg::new("1.0.0", "\"network\"");
p.file("bin/suid", "x", 0o4777);
p.link("bin/alias", "hello");
let pkg = p.write(&root);
store.unpack_store(&name, "1.0.0", &pkg, &expect).unwrap();
store.stage(&name, "1.0.0").unwrap();
let applied = store.apply_staged(|_| true).unwrap();
assert!(applied.store && !applied.apps);
assert!(root.join("store/apps").join(ID).join("app.toml").is_file());
assert_eq!(store.installed(&name).as_deref(), Some("1.0.0"));
assert_eq!(fs::read_to_string(root.join(&name).join("source")).unwrap().trim(), "https://github.com/fox/hello");
use std::os::unix::fs::PermissionsExt;
let mode = fs::metadata(root.join(&name).join("1.0.0/bin/suid")).unwrap().permissions().mode() & 0o7777;
assert_eq!(mode, 0o755);
// An unsigned update installs from the selected source.
let pkg = Pkg::new("1.1.0", "\"network\"").write(&root);
store.unpack_store(&name, "1.1.0", &pkg, &expect).unwrap();
// More permissions than approved.
let pkg = Pkg::new("1.1.0", "\"network\", \"devices\"").write(&root);
let err = store.unpack_store(&name, "1.1.0", &pkg, &expect).unwrap_err();
assert!(format!("{err:#}").contains("not approved"), "{err:#}");
// A symlink out of the package.
let mut p = Pkg::new("1.1.0", "\"network\"");
p.link("bin/evil", "../../../../etc/shadow");
let pkg = p.write(&root);
assert!(store.unpack_store(&name, "1.1.0", &pkg, &expect).is_err());
let mut p = Pkg::new("1.1.0", "\"network\"");
p.link("evil", "/etc/shadow");
let pkg = p.write(&root);
assert!(store.unpack_store(&name, "1.1.0", &pkg, &expect).is_err());
// Nothing half-unpacked is left behind.
assert!(!root.join(&name).join("1.1.0").exists());
assert!(!root.join(&name).join(".tmp-1.1.0").exists());
// Uninstall.
store.remove_store_app(ID).unwrap();
assert!(!root.join(&name).exists());
assert!(fs::symlink_metadata(root.join("store/apps").join(ID)).is_err());
fs::remove_dir_all(&root).unwrap();
}
#[test]
fn plan_holds_back_new_permissions() {
use sf_ipc::store::{Catalog, CatalogApp, Wanted, WantedApp};
let (root, store) = setup("plan");
let app = |perms: Vec<Permission>| CatalogApp {
id: ID.into(),
name: "Hello".into(),
version: "2.0.0".into(),
permissions: perms,
source: "https://github.com/fox/hello".into(),
..Default::default()
};
let mut wanted = Wanted::default();
wanted.apps.insert(ID.into(), WantedApp { source: "github.com/fox/hello".into(), permissions: vec![Permission::Network] });
let mut cat = Catalog { apps: vec![app(vec![Permission::Network])], ..Default::default() };
assert_eq!(crate::appstore::plan(&store, &wanted, &mut cat).len(), 1);
let mut cat = Catalog { apps: vec![app(vec![Permission::Network, Permission::Gpu])], ..Default::default() };
assert!(crate::appstore::plan(&store, &wanted, &mut cat).is_empty());
assert_eq!(cat.apps[0].blocked.as_deref(), Some("permissions"));
// Not wanted: nothing to do.
let mut cat = Catalog { apps: vec![app(vec![])], ..Default::default() };
assert!(crate::appstore::plan(&store, &Wanted::default(), &mut cat).is_empty());
fs::remove_dir_all(&root).unwrap();
}
}