backend.rs (8200B)
1 //! What the updater needs from the system, behind one trait so the screens can be developed and 2 //! tested without root, rpm-ostree or a registry. `Mock` stands in for all of it; the real one is 3 //! in system.rs. 4 5 use std::sync::mpsc::Sender; 6 use std::time::Duration; 7 8 /// Where updates come from unless the person picks another registry. 9 pub const DEFAULT_REGISTRY: &str = "ghcr.io/sector-f-labs/sector-f-linux:latest"; 10 11 /// The system as it is booted. 12 #[derive(Debug, Clone, PartialEq)] 13 pub struct Status { 14 /// The image the system follows, without the transport: `ghcr.io/sector-f-labs/sector-f-linux:latest`. 15 pub image: String, 16 /// `sha256:...` of the booted image. 17 pub digest: String, 18 pub version: String, 19 /// An update (or a switch) is staged and waits for a restart. 20 pub staged: bool, 21 /// An older build is kept, so there is something to roll back to. 22 pub can_roll_back: bool, 23 } 24 25 /// What a registry has, against what is booted. 26 #[derive(Debug, Clone, PartialEq)] 27 pub enum Availability { 28 UpToDate, 29 /// The registry's image is a different build from the booted one. 30 Newer { 31 digest: String, 32 }, 33 } 34 35 /// What changes the system. Each runs as root, through `patina-update` and pkexec. 36 #[derive(Debug, Clone, PartialEq)] 37 pub enum Action { 38 /// Fetch the newest build of the image the system already follows. 39 Update, 40 /// Follow another image (registry) from now on, and fetch it. 41 Switch(String), 42 /// Boot the previous build at the next restart. 43 RollBack, 44 } 45 46 /// What an action reports while it runs. 47 #[derive(Debug, Clone, PartialEq)] 48 pub enum Event { 49 /// A line of what is happening. 50 Line(String), 51 Done, 52 Failed(String), 53 } 54 55 pub trait Backend: Send + Sync { 56 fn status(&self) -> Result<Status, String>; 57 /// Asks the registry for `image`'s digest and compares it with the booted one. Needs no root. 58 fn check(&self, image: &str) -> Result<Availability, String>; 59 /// Returns at once; the events come over `tx` from a thread of the backend's, the last one 60 /// `Done` or `Failed`. 61 fn run(&self, action: Action, tx: Sender<Event>); 62 fn restart(&self) -> Result<(), String>; 63 } 64 65 /// `ghcr.io/org/name`, `ghcr.io/org/name:tag`, `host:5000/name@sha256:...`: what `rpm-ostree rebase` 66 /// takes after its transport. The root helper checks the same rule (`patina-update`); keep them equal. 67 pub fn valid_image(image: &str) -> bool { 68 let (path, rest) = match image.split_once('@') { 69 Some((path, digest)) => { 70 let hex = digest.strip_prefix("sha256:").unwrap_or(""); 71 if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) { 72 return false; 73 } 74 (path, None) 75 } 76 None => match image.rsplit_once(':') { 77 // A colon after the last slash is a tag; before it, a port. 78 Some((path, tag)) if !tag.contains('/') => (path, Some(tag)), 79 _ => (image, None), 80 }, 81 }; 82 if let Some(tag) = rest 83 && (tag.is_empty() 84 || tag.len() > 128 85 || !tag 86 .bytes() 87 .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))) 88 { 89 return false; 90 } 91 let Some((host, repo)) = path.split_once('/') else { 92 return false; 93 }; 94 // Not starting with a dash: the name must never be taken for an option by what it is passed to. 95 let (name, port) = match host.split_once(':') { 96 Some((name, port)) => (name, Some(port)), 97 None => (host, None), 98 }; 99 host.starts_with(|c: char| c.is_ascii_alphanumeric()) 100 && name 101 .bytes() 102 .all(|b| b.is_ascii_alphanumeric() || b"-.".contains(&b)) 103 && port 104 .is_none_or(|p| !p.is_empty() && p.len() <= 5 && p.bytes().all(|b| b.is_ascii_digit())) 105 && !repo.is_empty() 106 && repo.split('/').all(|part| { 107 !part.is_empty() 108 && !part.starts_with(['.', '-']) 109 && part 110 .bytes() 111 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b)) 112 }) 113 } 114 115 /// The image with its tag made explicit (`:latest`), so two spellings of the same image compare equal. 116 pub fn with_tag(image: &str) -> String { 117 let last = image.rsplit('/').next().unwrap_or(image); 118 if image.contains('@') || last.contains(':') { 119 image.to_string() 120 } else { 121 format!("{image}:latest") 122 } 123 } 124 125 /// `sha256:0123456789ab`: enough to tell builds apart on screen. 126 pub fn short_digest(digest: &str) -> String { 127 digest.chars().take("sha256:".len() + 12).collect() 128 } 129 130 /// A fake system following the default registry, with an update waiting, and an update that takes 131 /// `Mock::SECONDS`, or ends in an error when told to fail. 132 pub struct Mock { 133 pub fail: bool, 134 } 135 136 impl Mock { 137 pub const SECONDS: u64 = 6; 138 } 139 140 impl Backend for Mock { 141 fn status(&self) -> Result<Status, String> { 142 Ok(Status { 143 image: DEFAULT_REGISTRY.into(), 144 digest: "sha256:533a3e97725836733f0bd604350574a4d38179f8f942046dfe41663aa8b0eb70" 145 .into(), 146 version: "45.20261127.0".into(), 147 staged: false, 148 can_roll_back: true, 149 }) 150 } 151 152 fn check(&self, image: &str) -> Result<Availability, String> { 153 if image.starts_with("down.") { 154 return Err("could not reach down.example: no such host".into()); 155 } 156 Ok(Availability::Newer { 157 digest: "sha256:9f2c41d7aa30b5e8c1d64f0a7e3b92c8d5106fa4e7b3c29d8a05e6f1b47c3d20" 158 .into(), 159 }) 160 } 161 162 fn run(&self, action: Action, tx: Sender<Event>) { 163 let fail = self.fail; 164 std::thread::spawn(move || { 165 let lines = match &action { 166 Action::Update => vec![ 167 "Pulling the new image", 168 "Importing layers", 169 "Staging the deployment", 170 ], 171 Action::Switch(image) => vec![ 172 "Pulling the image", 173 "Importing layers", 174 "Staging the deployment", 175 image.as_str(), 176 ], 177 Action::RollBack => vec!["Choosing the previous deployment"], 178 }; 179 for line in lines { 180 std::thread::sleep(Duration::from_millis(Mock::SECONDS * 100)); 181 let _ = tx.send(Event::Line(line.into())); 182 } 183 let _ = tx.send(if fail { 184 Event::Failed("rpm-ostree: Failed to pull: no space left on device".into()) 185 } else { 186 Event::Done 187 }); 188 }); 189 } 190 191 fn restart(&self) -> Result<(), String> { 192 Ok(()) 193 } 194 } 195 196 #[cfg(test)] 197 mod tests { 198 use super::*; 199 200 #[test] 201 fn images_that_rpm_ostree_takes() { 202 for image in [ 203 DEFAULT_REGISTRY, 204 "ghcr.io/sector-f-labs/sector-f-linux", 205 "registry.example.org:5000/team/os:2026-11", 206 "localhost:5000/os@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", 207 ] { 208 assert!(valid_image(image), "{image}"); 209 } 210 } 211 212 #[test] 213 fn images_that_it_must_not() { 214 for image in [ 215 "", 216 "nohost", 217 "ghcr.io/", 218 "ghcr.io/Org/Name", 219 "ghcr.io/org/name:", 220 "ghcr.io/org/name:ta g", 221 "ghcr.io/org/name;rm -rf /", 222 "--help/x", 223 "ghcr.io/org/../name", 224 "ghcr.io/org/name@sha256:abc", 225 "ostree-unverified-registry:ghcr.io/org/name", 226 ] { 227 assert!(!valid_image(image), "{image}"); 228 } 229 } 230 231 #[test] 232 fn tags_are_made_explicit() { 233 assert_eq!(with_tag("ghcr.io/o/n"), "ghcr.io/o/n:latest"); 234 assert_eq!(with_tag("ghcr.io/o/n:v1"), "ghcr.io/o/n:v1"); 235 assert_eq!(with_tag("localhost:5000/n"), "localhost:5000/n:latest"); 236 } 237 238 #[test] 239 fn digests_are_shortened() { 240 assert_eq!( 241 short_digest("sha256:533a3e97725836733f0b"), 242 "sha256:533a3e977258" 243 ); 244 } 245 }