use crate::ids::{check_id, check_text, check_unique};
use crate::rollout::RolloutPlan;
use crate::target::Rule;
use crate::{Error, Hash32, Result, Timestamp};
use semver::Version;
use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;
pub const MAX_FILES: usize = 10_000;
pub const MAX_CAPABILITIES: usize = 256;
pub const MAX_PATH: usize = 512;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[allow(missing_docs)]
pub enum Platform {
Linux,
Macos,
Windows,
Android,
Ios,
Freebsd,
Openbsd,
Ghostbsd,
Dragonfly,
}
impl Platform {
pub fn as_str(self) -> &'static str {
match self {
Self::Linux => "linux",
Self::Macos => "macos",
Self::Windows => "windows",
Self::Android => "android",
Self::Ios => "ios",
Self::Freebsd => "freebsd",
Self::Openbsd => "openbsd",
Self::Ghostbsd => "ghostbsd",
Self::Dragonfly => "dragonfly",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[allow(missing_docs)]
pub enum Arch {
X86_64,
Aarch64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[allow(missing_docs)]
pub enum PackageFormat {
TarGz,
Zip,
Deb,
Rpm,
PkgTarZst,
Nix,
Homebrew,
Winget,
App,
Dmg,
Exe,
Msi,
Apk,
Ipa,
BsdPkg,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InstallMode {
Swap,
PlatformInstaller,
PrivilegedPackageManager,
NotifyOnly,
}
impl PackageFormat {
pub fn install_mode(self) -> InstallMode {
match self {
Self::TarGz | Self::Zip | Self::App | Self::Exe => InstallMode::Swap,
Self::Dmg | Self::Msi | Self::Apk | Self::Ipa => InstallMode::PlatformInstaller,
Self::Deb | Self::Rpm | Self::BsdPkg => InstallMode::PrivilegedPackageManager,
Self::PkgTarZst | Self::Nix | Self::Homebrew | Self::Winget => InstallMode::NotifyOnly,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FullPackage {
pub platform: Platform,
pub arch: Arch,
pub format: PackageFormat,
pub signing_identity: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DartPatch {
pub engine_hash: String,
pub platform: Platform,
pub arch: Arch,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum UpdateKind {
Assets,
Wasm {
host_abi: u32,
},
Full(FullPackage),
DartPatch(DartPatch),
StoreNotice {
url: String,
},
}
impl UpdateKind {
pub fn name(&self) -> &'static str {
match self {
Self::Assets => "assets",
Self::Wasm { .. } => "wasm",
Self::Full(_) => "full",
Self::DartPatch(_) => "dart-patch",
Self::StoreNotice { .. } => "store-notice",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[allow(missing_docs)]
pub enum Severity {
Low,
Medium,
High,
Critical,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SecurityLabel {
pub severity: Severity,
pub advisory: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Labels {
#[serde(default)]
pub security: Option<SecurityLabel>,
#[serde(default)]
pub recommended: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileEntry {
pub path: String,
pub size: u64,
pub blake3: Hash32,
}
impl FileEntry {
pub fn describe(path: &str, data: &[u8]) -> Self {
Self { path: path.to_owned(), size: data.len() as u64, blake3: Hash32::of(data) }
}
pub fn verify(&self, data: &[u8]) -> Result<()> {
let mut v = self.verifier();
v.update(data)?;
v.finish()
}
pub fn verifier(&self) -> FileVerifier<'_> {
FileVerifier { entry: self, hasher: blake3::Hasher::new(), seen: 0 }
}
fn validate(&self) -> Result<()> {
let p = &self.path;
let bad = p.is_empty()
|| p.len() > MAX_PATH
|| p.starts_with('/')
|| p.contains('\\')
|| p.contains('\0')
|| p.split('/').any(|c| c.is_empty() || c == "." || c == "..")
|| p.as_bytes().get(1) == Some(&b':');
if bad {
return Err(Error::File { path: p.clone(), reason: "unsafe or malformed path".into() });
}
Ok(())
}
}
pub struct FileVerifier<'a> {
entry: &'a FileEntry,
hasher: blake3::Hasher,
seen: u64,
}
impl FileVerifier<'_> {
pub fn update(&mut self, data: &[u8]) -> Result<()> {
self.seen = self.seen.saturating_add(data.len() as u64);
if self.seen > self.entry.size {
return Err(Error::File { path: self.entry.path.clone(), reason: "larger than declared".into() });
}
self.hasher.update(data);
Ok(())
}
pub fn finish(self) -> Result<()> {
if self.seen != self.entry.size {
return Err(Error::File { path: self.entry.path.clone(), reason: "size mismatch".into() });
}
if Hash32::from(self.hasher.finalize()) != self.entry.blake3 {
return Err(Error::File { path: self.entry.path.clone(), reason: "hash mismatch".into() });
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct UpdateManifest {
pub app: String,
pub channel: String,
pub update_id: String,
pub seq: u64,
pub kind: UpdateKind,
pub version: Version,
#[serde(default)]
pub base_releases: Vec<String>,
#[serde(default)]
pub files: Vec<FileEntry>,
#[serde(default)]
pub min_client: Option<Version>,
#[serde(default)]
pub max_client: Option<Version>,
#[serde(default)]
pub capabilities: Vec<String>,
#[serde(default)]
pub labels: Labels,
#[serde(default)]
pub targeting: Option<Rule>,
#[serde(default)]
pub rollout: Option<RolloutPlan>,
#[serde(default)]
pub rollback_of: Option<String>,
#[serde(default)]
pub notes: String,
pub created: Timestamp,
pub expires: Timestamp,
}
impl UpdateManifest {
pub fn validate(&self) -> Result<()> {
check_id("app", &self.app)?;
check_id("channel", &self.channel)?;
check_id("update id", &self.update_id)?;
if self.expires <= self.created {
return Err(Error::invalid("manifest", "expires must be after created"));
}
for b in &self.base_releases {
check_id("base release", b)?;
}
if let (Some(lo), Some(hi)) = (&self.min_client, &self.max_client)
&& lo > hi
{
return Err(Error::invalid("manifest", "min_client above max_client"));
}
if self.files.len() > MAX_FILES {
return Err(Error::invalid("manifest", format!("more than {MAX_FILES} files")));
}
let mut paths = BTreeSet::new();
for f in &self.files {
f.validate()?;
if !paths.insert(f.path.as_str()) {
return Err(Error::File { path: f.path.clone(), reason: "listed twice".into() });
}
}
match &self.kind {
UpdateKind::StoreNotice { url } => {
if !self.files.is_empty() {
return Err(Error::invalid("manifest", "a store notice carries no files"));
}
if !url.starts_with("https://") || url.len() > 2048 {
return Err(Error::invalid("manifest", "store url must be https"));
}
}
_ if self.files.is_empty() => return Err(Error::invalid("manifest", "no files")),
UpdateKind::Full(p) => check_id("signing identity", &p.signing_identity)?,
UpdateKind::DartPatch(p) => check_id("engine hash", &p.engine_hash)?,
UpdateKind::Assets | UpdateKind::Wasm { .. } => {}
}
if self.capabilities.len() > MAX_CAPABILITIES {
return Err(Error::invalid("manifest", format!("more than {MAX_CAPABILITIES} capabilities")));
}
for c in &self.capabilities {
check_id("capability", c)?;
}
check_unique("capabilities", &self.capabilities)?;
if let Some(s) = &self.labels.security {
check_text("advisory", &s.advisory)?;
}
check_text("notes", &self.notes)?;
if let Some(r) = &self.rollback_of {
check_id("rollback_of", r)?;
}
if let Some(rule) = &self.targeting {
rule.validate()?;
}
if let Some(plan) = &self.rollout {
plan.validate()?;
}
Ok(())
}
pub fn target(&self) -> String {
format!("{}/{}", self.app, self.channel)
}
pub fn total_size(&self) -> u64 {
self.files.iter().map(|f| f.size).fold(0u64, u64::saturating_add)
}
}