rebuilderd_common/
auth.rs1use crate::errors::*;
2use serde::Deserialize;
3use std::env;
4use std::fs;
5use std::path::Path;
6
7const SYSTEM_CONFIG_PATH: &str = "/etc/rebuilderd.conf";
8const SYSTEM_COOKIE_PATH: &str = "/var/lib/rebuilderd/auth-cookie";
9
10#[derive(Debug, Default, Deserialize)]
11pub struct Config {
12 #[serde(default)]
13 pub auth: AuthConfig,
14}
15
16#[derive(Debug, Default, Clone, Deserialize)]
17pub struct AuthConfig {
18 pub cookie: Option<String>,
19}
20
21impl AuthConfig {
22 pub fn update(&mut self, c: AuthConfig) {
23 if c.cookie.is_some() {
24 self.cookie = c.cookie;
25 }
26 }
27}
28
29fn read_cookie_from_config<P: AsRef<Path>>(path: P) -> Result<Option<String>> {
30 debug!("Attempting reading cookie from config: {:?}", path.as_ref());
31 if let Ok(buf) = fs::read_to_string(path.as_ref()) {
32 let config = toml::from_str::<Config>(&buf)?;
33 debug!("Found cookie in config {:?}", path.as_ref());
34 Ok(config.auth.cookie)
35 } else {
36 Ok(None)
37 }
38}
39
40pub fn read_cookie_from_file<P: AsRef<Path>>(path: P) -> Result<String> {
41 debug!("Attempting reading cookie from file: {:?}", path.as_ref());
42 let cookie = fs::read_to_string(path.as_ref())?;
43 debug!("Found cookie in file {:?}", path.as_ref());
44 Ok(cookie.trim().to_string())
45}
46
47pub fn find_auth_cookie() -> Result<String> {
48 if let Ok(cookie_path) = env::var("REBUILDERD_COOKIE_PATH") {
49 debug!("Using auth cookie from cookie path env: {cookie_path:?}");
50 return read_cookie_from_file(cookie_path);
51 }
52
53 if let Some(config_dir) = dirs_next::config_dir() {
54 let path = config_dir.join("rebuilderd.conf");
55 if let Some(cookie) = read_cookie_from_config(&path)? {
56 debug!("Using auth cookie from user-config: {path:?}");
57 return Ok(cookie);
58 }
59 }
60
61 if let Some(cookie) = read_cookie_from_config(SYSTEM_CONFIG_PATH)? {
62 debug!("Using auth cookie from system-config: {SYSTEM_CONFIG_PATH:?}");
63 return Ok(cookie);
64 }
65
66 if let Ok(cookie) = read_cookie_from_file(SYSTEM_COOKIE_PATH) {
67 debug!("Using auth cookie from system-daemon: {SYSTEM_COOKIE_PATH:?}");
68 return Ok(cookie);
69 }
70
71 if let Some(data_dir) = dirs_next::data_dir() {
72 let path = data_dir.join("rebuilderd-auth-cookie");
73 if let Ok(cookie) = read_cookie_from_file(&path) {
74 debug!("Using auth cookie from user-daemon: {path:?}");
75 return Ok(cookie);
76 }
77 }
78
79 bail!("Failed to find auth cookie anywhere")
80}