sector-f-linux

Sector F Linux
git clone https://git.sectorflabs.com/sector-f-linux.git
Log | Files | Refs | README | LICENSE

backend.rs (10631B)


      1 //! What the greeter needs from the system, behind one trait so the screens can be developed and
      2 //! tested without greetd: who can log in, whether this is the first run, logging in, making the
      3 //! first account, and power. `Mock` stands in for all of it; the real one (greetd's socket,
      4 //! AccountsService, logind) is in system.rs, per ADR-0012.
      5 
      6 use std::sync::Mutex;
      7 use std::time::Duration;
      8 
      9 #[derive(Debug, Clone, PartialEq)]
     10 pub struct User {
     11     pub name: String,
     12     pub full_name: String,
     13 }
     14 
     15 #[derive(Debug, Clone, Copy, PartialEq)]
     16 pub enum Power {
     17     Reboot,
     18     PowerOff,
     19 }
     20 
     21 #[derive(Debug, Clone, PartialEq)]
     22 pub enum LoginError {
     23     /// The password was refused: the person can try again.
     24     Wrong,
     25     /// Something else failed: shown as it is.
     26     Problem(String),
     27 }
     28 
     29 /// How a Wi-Fi network is secured, as far as the setup can join it: open, or with a password
     30 /// (WPA or WPA2 personal, or WPA3's SAE). Networks it cannot join (WEP, a work network with its own
     31 /// login) are not offered.
     32 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
     33 pub enum Security {
     34     Open,
     35     Psk,
     36     Sae,
     37 }
     38 
     39 /// A Wi-Fi network in range.
     40 #[derive(Debug, Clone, PartialEq)]
     41 pub struct Network {
     42     pub ssid: String,
     43     /// 0 to 100.
     44     pub strength: u8,
     45     pub security: Security,
     46 }
     47 
     48 impl Network {
     49     pub fn secured(&self) -> bool {
     50         self.security != Security::Open
     51     }
     52 }
     53 
     54 /// The networks to show: one per name, the strongest, strongest first, hidden ones (no name) left out.
     55 pub fn tidy(mut networks: Vec<Network>) -> Vec<Network> {
     56     networks.retain(|n| !n.ssid.is_empty());
     57     networks.sort_by(|a, b| b.strength.cmp(&a.strength).then(a.ssid.cmp(&b.ssid)));
     58     let mut seen = std::collections::HashSet::new();
     59     networks.retain(|n| seen.insert(n.ssid.clone()));
     60     networks
     61 }
     62 
     63 /// Called from worker threads, since PAM and D-Bus can take seconds (a wrong password costs a
     64 /// delay by design), so a backend is shared and answers `&self`.
     65 pub trait Backend: Send + Sync {
     66     /// Who can log in, in the order to show them.
     67     fn users(&self) -> Vec<User>;
     68     /// No human account can log in yet: show the setup, not the login.
     69     fn first_run(&self) -> bool;
     70     /// Checks the password and, if it is right, starts the session.
     71     fn login(&self, user: &str, password: &str) -> Result<(), LoginError>;
     72     /// Makes the first account (ADR-0012: through AccountsService, which polkit allows only now).
     73     fn create_first_user(
     74         &self,
     75         full_name: &str,
     76         username: &str,
     77         password: &str,
     78     ) -> Result<(), String>;
     79     fn power(&self, action: Power) -> Result<(), String>;
     80     /// The time zones there are, as `Europe/Stockholm`, in order (ADR-0019, the setup's clock).
     81     fn timezones(&self) -> Vec<String>;
     82     /// The one this machine is on now.
     83     fn timezone(&self) -> String;
     84     /// Sets it, through timedated, which polkit lets the greeter do only on the first run.
     85     fn set_timezone(&self, zone: &str) -> Result<(), String>;
     86     /// The computer's name now (ADR-0019, the setup's name step).
     87     fn hostname(&self) -> String;
     88     /// Sets it, through hostnamed, which polkit lets the greeter do only on the first run.
     89     fn set_hostname(&self, name: &str) -> Result<(), String>;
     90     /// Whether this machine has Wi-Fi: without it the setup has no Wi-Fi step.
     91     fn wifi_available(&self) -> bool;
     92     /// Asks for a new scan and returns the networks in range (`tidy`), which can take a moment.
     93     fn wifi_networks(&self) -> Vec<Network>;
     94     /// Joins a network and saves it for every user (polkit lets the greeter only on the first run);
     95     /// returns when it is up, or says why not.
     96     fn wifi_connect(&self, ssid: &str, password: &str) -> Result<(), String>;
     97 }
     98 
     99 /// A backend with accounts in memory, for the screens and the tests. The password that works is
    100 /// `sectorf`; logging in takes a moment, so the busy state shows.
    101 pub struct Mock {
    102     users: Mutex<Vec<User>>,
    103     delay: Duration,
    104     zone: Mutex<String>,
    105     host: Mutex<String>,
    106     wifi: bool,
    107 }
    108 
    109 /// The zones the mock knows, as a few of the real ones.
    110 pub const MOCK_ZONES: &[&str] = &[
    111     "Africa/Cairo",
    112     "America/Los_Angeles",
    113     "America/New_York",
    114     "America/Sao_Paulo",
    115     "Asia/Kolkata",
    116     "Asia/Tokyo",
    117     "Australia/Sydney",
    118     "Europe/Berlin",
    119     "Europe/London",
    120     "Europe/Stockholm",
    121     "Pacific/Auckland",
    122     "UTC",
    123 ];
    124 
    125 pub const MOCK_PASSWORD: &str = "sectorf";
    126 /// A password that makes the mock fail the way a login service that is down does.
    127 pub const MOCK_BROKEN: &str = "broken";
    128 
    129 impl Mock {
    130     pub fn new(users: &[(&str, &str)], delay: Duration) -> Self {
    131         Self {
    132             users: Mutex::new(
    133                 users
    134                     .iter()
    135                     .map(|(n, f)| User {
    136                         name: (*n).into(),
    137                         full_name: (*f).into(),
    138                     })
    139                     .collect(),
    140             ),
    141             delay,
    142             zone: Mutex::new("UTC".into()),
    143             host: Mutex::new("sectorf".into()),
    144             wifi: false,
    145         }
    146     }
    147 
    148     /// A machine with accounts already.
    149     pub fn with_users() -> Self {
    150         Self::new(
    151             &[("alice", "Alice Example"), ("bob", "Bob Prototype")],
    152             Duration::from_millis(700),
    153         )
    154     }
    155 
    156     /// A machine fresh from the install: nobody can log in, and it has Wi-Fi.
    157     pub fn first_run() -> Self {
    158         Self::new(&[], Duration::from_millis(700)).with_wifi()
    159     }
    160 
    161     /// The same, with Wi-Fi: four networks in range.
    162     pub fn with_wifi(mut self) -> Self {
    163         self.wifi = true;
    164         self
    165     }
    166 }
    167 
    168 impl Backend for Mock {
    169     fn users(&self) -> Vec<User> {
    170         self.users.lock().unwrap().clone()
    171     }
    172 
    173     fn first_run(&self) -> bool {
    174         self.users.lock().unwrap().is_empty()
    175     }
    176 
    177     fn login(&self, user: &str, password: &str) -> Result<(), LoginError> {
    178         std::thread::sleep(self.delay);
    179         if password == MOCK_BROKEN {
    180             return Err(LoginError::Problem("Can't reach the login service".into()));
    181         }
    182         let known = self.users.lock().unwrap().iter().any(|u| u.name == user);
    183         if known && password == MOCK_PASSWORD {
    184             Ok(())
    185         } else {
    186             Err(LoginError::Wrong)
    187         }
    188     }
    189 
    190     fn create_first_user(
    191         &self,
    192         full_name: &str,
    193         username: &str,
    194         _password: &str,
    195     ) -> Result<(), String> {
    196         std::thread::sleep(self.delay);
    197         let mut users = self.users.lock().unwrap();
    198         if !users.is_empty() {
    199             return Err("This computer is already set up".into());
    200         }
    201         users.push(User {
    202             name: username.into(),
    203             full_name: full_name.into(),
    204         });
    205         Ok(())
    206     }
    207 
    208     fn power(&self, _action: Power) -> Result<(), String> {
    209         Ok(())
    210     }
    211 
    212     fn timezones(&self) -> Vec<String> {
    213         MOCK_ZONES.iter().map(|z| (*z).to_string()).collect()
    214     }
    215 
    216     fn timezone(&self) -> String {
    217         self.zone.lock().unwrap().clone()
    218     }
    219 
    220     fn set_timezone(&self, zone: &str) -> Result<(), String> {
    221         std::thread::sleep(self.delay);
    222         if !MOCK_ZONES.contains(&zone) {
    223             return Err(format!("could not set the time zone: unknown zone {zone}"));
    224         }
    225         *self.zone.lock().unwrap() = zone.into();
    226         Ok(())
    227     }
    228 
    229     fn hostname(&self) -> String {
    230         self.host.lock().unwrap().clone()
    231     }
    232 
    233     fn set_hostname(&self, name: &str) -> Result<(), String> {
    234         std::thread::sleep(self.delay);
    235         if name == MOCK_BROKEN {
    236             return Err("could not set the name: hostnamed is not running".into());
    237         }
    238         crate::model::check_hostname(name).map_err(str::to_string)?;
    239         *self.host.lock().unwrap() = name.into();
    240         Ok(())
    241     }
    242 
    243     fn wifi_available(&self) -> bool {
    244         self.wifi
    245     }
    246 
    247     fn wifi_networks(&self) -> Vec<Network> {
    248         let net = |ssid: &str, strength, security| Network {
    249             ssid: ssid.into(),
    250             strength,
    251             security,
    252         };
    253         tidy(vec![
    254             net("Neighbour", 38, Security::Psk),
    255             net("Home-5G", 92, Security::Psk),
    256             net("CoffeeShop", 71, Security::Open),
    257             net("Home-5G", 55, Security::Psk),
    258             net("", 60, Security::Psk),
    259             net("Office-Guest", 24, Security::Sae),
    260         ])
    261     }
    262 
    263     /// Open networks join; a secured one wants the password `sectorf`.
    264     fn wifi_connect(&self, ssid: &str, password: &str) -> Result<(), String> {
    265         std::thread::sleep(self.delay);
    266         let Some(network) = self.wifi_networks().into_iter().find(|n| n.ssid == ssid) else {
    267             return Err(format!("could not join {ssid}: it is out of range"));
    268         };
    269         if network.secured() && password != MOCK_PASSWORD {
    270             return Err(format!(
    271                 "could not join {ssid}: the password was not accepted"
    272             ));
    273         }
    274         Ok(())
    275     }
    276 }
    277 
    278 #[cfg(test)]
    279 mod tests {
    280     use super::*;
    281 
    282     fn quick(users: &[(&str, &str)]) -> Mock {
    283         Mock::new(users, Duration::ZERO)
    284     }
    285 
    286     #[test]
    287     fn a_fresh_machine_is_first_run_until_an_account_exists() {
    288         let m = quick(&[]);
    289         assert!(m.first_run());
    290         m.create_first_user("Alice Example", "alice", "pw").unwrap();
    291         assert!(!m.first_run());
    292         assert_eq!(m.users()[0].name, "alice");
    293         assert!(m.create_first_user("Mallory", "mallory", "pw").is_err());
    294         assert_eq!(m.users().len(), 1, "no second first account");
    295     }
    296 
    297     #[test]
    298     fn the_networks_are_one_per_name_strongest_first_and_hidden_ones_left_out() {
    299         let net = |ssid: &str, strength| Network {
    300             ssid: ssid.into(),
    301             strength,
    302             security: Security::Psk,
    303         };
    304         let shown = tidy(vec![
    305             net("b", 40),
    306             net("a", 40),
    307             net("", 99),
    308             net("a", 80),
    309             net("c", 10),
    310         ]);
    311         let names: Vec<_> = shown
    312             .iter()
    313             .map(|n| (n.ssid.as_str(), n.strength))
    314             .collect();
    315         assert_eq!(names, [("a", 80), ("b", 40), ("c", 10)]);
    316     }
    317 
    318     #[test]
    319     fn logging_in_checks_the_password_and_the_user() {
    320         let m = quick(&[("alice", "Alice Example")]);
    321         assert_eq!(m.login("alice", MOCK_PASSWORD), Ok(()));
    322         assert_eq!(m.login("alice", "nope"), Err(LoginError::Wrong));
    323         assert_eq!(m.login("nobody", MOCK_PASSWORD), Err(LoginError::Wrong));
    324         assert!(matches!(
    325             m.login("alice", MOCK_BROKEN),
    326             Err(LoginError::Problem(_))
    327         ));
    328     }
    329 }