webbluetooth_core/
grants.rs1use crate::registry::Grant;
46use crate::uuid::BluetoothUuid;
47use std::collections::BTreeMap;
48use std::path::{Path, PathBuf};
49
50const HEADER: &str = "# webbluetooth grants v1";
52
53const WILDCARD: &str = "*";
58
59#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct Stored {
62 pub name: Option<String>,
64 pub grant: Grant,
66}
67
68#[derive(Debug, Clone)]
70pub struct GrantStore {
71 path: PathBuf,
72}
73
74impl GrantStore {
75 pub fn new(path: impl Into<PathBuf>) -> Self {
77 Self { path: path.into() }
78 }
79
80 pub fn path(&self) -> &Path {
82 &self.path
83 }
84
85 pub fn load(&self) -> BTreeMap<String, Stored> {
91 let Ok(text) = std::fs::read_to_string(&self.path) else {
92 return BTreeMap::new();
93 };
94 parse(&text)
95 }
96
97 pub fn save(&self, devices: &BTreeMap<String, Stored>) -> std::io::Result<()> {
103 if let Some(parent) = self.path.parent() {
104 if !parent.as_os_str().is_empty() {
105 std::fs::create_dir_all(parent)?;
106 }
107 }
108 let temporary = self.path.with_extension("tmp");
109 std::fs::write(&temporary, render(devices))?;
110 restrict(&temporary)?;
111 std::fs::rename(&temporary, &self.path)
112 }
113}
114
115#[cfg(unix)]
117fn restrict(path: &Path) -> std::io::Result<()> {
118 use std::os::unix::fs::PermissionsExt;
119 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
120}
121
122#[cfg(not(unix))]
124fn restrict(_path: &Path) -> std::io::Result<()> {
125 Ok(())
126}
127
128fn render(devices: &BTreeMap<String, Stored>) -> String {
129 let mut out = String::from(HEADER);
130 out.push('\n');
131 for (id, stored) in devices {
132 let services: Vec<&str> = if stored.grant.permits_all_services() {
137 vec![WILDCARD]
138 } else {
139 stored.grant.services.iter().map(|u| u.as_str()).collect()
140 };
141 let companies: Vec<String> = if stored.grant.permits_all_manufacturer_data() {
142 vec![WILDCARD.to_owned()]
143 } else {
144 stored
145 .grant
146 .manufacturer_data
147 .iter()
148 .map(|c| c.to_string())
149 .collect()
150 };
151 let name = stored.name.as_deref().unwrap_or("");
155 let name: String = name.chars().filter(|c| *c != '\t' && *c != '\n').collect();
156 out.push_str(&format!(
157 "{id}\t{name}\t{}\t{}\n",
158 services.join(","),
159 companies.join(",")
160 ));
161 }
162 out
163}
164
165fn parse(text: &str) -> BTreeMap<String, Stored> {
166 let mut out = BTreeMap::new();
167 for line in text.lines() {
168 let line = line.trim_end_matches(['\r', '\n']);
172 if line.is_empty() || line.starts_with('#') {
173 continue;
174 }
175 let mut fields = line.split('\t');
176 let (Some(id), Some(name), Some(services)) = (fields.next(), fields.next(), fields.next())
177 else {
178 continue; };
180 let companies = fields.next().unwrap_or("");
181 if id.is_empty() {
182 continue;
183 }
184 out.insert(
185 id.to_owned(),
186 Stored {
187 name: (!name.is_empty()).then(|| name.to_owned()),
188 grant: {
189 let mut grant = Grant::new();
190 grant.services = services
191 .split(',')
192 .filter(|s| !s.is_empty())
193 .filter_map(|s| BluetoothUuid::parse(s).ok())
194 .collect();
195 grant.manufacturer_data = companies
196 .split(',')
197 .filter(|s| !s.is_empty())
198 .filter_map(|s| s.parse().ok())
199 .collect();
200 #[cfg(feature = "unrestricted")]
201 {
202 grant.all_services = services.split(',').any(|field| field == WILDCARD);
203 grant.all_manufacturer_data =
204 companies.split(',').any(|field| field == WILDCARD);
205 }
206 grant
210 },
211 },
212 );
213 }
214 out
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220
221 fn stored(services: &[u16], companies: &[u16], name: Option<&str>) -> Stored {
222 Stored {
223 name: name.map(str::to_owned),
224 grant: {
225 let mut grant = Grant::new();
226 grant.services = services
227 .iter()
228 .map(|u| BluetoothUuid::from_u16(*u))
229 .collect();
230 grant.manufacturer_data = companies.to_vec();
231 grant
232 },
233 }
234 }
235
236 #[test]
241 fn a_grant_with_no_services_round_trips() {
242 let mut devices = BTreeMap::new();
243 devices.insert("11:22:33:44:55:66".to_owned(), stored(&[], &[], None));
244 assert_eq!(parse(&render(&devices)), devices);
245 }
246
247 #[test]
248 fn a_grant_survives_a_round_trip() {
249 let mut devices = BTreeMap::new();
250 devices.insert(
251 "AA:BB:CC:DD:EE:FF".to_owned(),
252 stored(&[0x180D, 0x180F], &[0x004C], Some("Heart Rate Belt")),
253 );
254 devices.insert("11:22:33:44:55:66".to_owned(), stored(&[], &[], None));
255
256 let back = parse(&render(&devices));
257 assert_eq!(back, devices);
258 }
259
260 #[test]
263 fn a_name_cannot_inject_another_record() {
264 let mut devices = BTreeMap::new();
265 devices.insert(
266 "AA:BB:CC:DD:EE:FF".to_owned(),
267 stored(
268 &[0x180F],
269 &[],
270 Some("evil\tx\t0000180d-0000-1000-8000-00805f9b34fb\n99:99:99:99:99:99\thi\t"),
271 ),
272 );
273 let back = parse(&render(&devices));
274 assert_eq!(back.len(), 1, "one device in, one device out");
275 assert!(
276 !back.contains_key("99:99:99:99:99:99"),
277 "the name must not have created a second grant"
278 );
279 let only = back.values().next().unwrap();
281 assert_eq!(only.grant.services.len(), 1);
282 }
283
284 #[test]
286 fn a_damaged_store_reads_as_empty_rather_than_failing() {
287 assert!(parse("").is_empty());
288 assert!(parse("not a record").is_empty());
289 assert!(parse("# only a comment\n").is_empty());
290 let mixed = format!(
292 "{HEADER}\ngarbage\nAA:BB:CC:DD:EE:FF\t\t0000180f-0000-1000-8000-00805f9b34fb\t\n"
293 );
294 assert_eq!(parse(&mixed).len(), 1);
295 }
296
297 #[test]
299 fn a_malformed_uuid_is_dropped_not_guessed() {
300 let line = format!("{HEADER}\ndev\t\tnot-a-uuid,0000180f-0000-1000-8000-00805f9b34fb\t\n");
301 let back = parse(&line);
302 let grant = &back.get("dev").unwrap().grant;
303 assert_eq!(grant.services.len(), 1, "only the one that parsed");
304 }
305
306 #[test]
311 #[cfg_attr(miri, ignore = "opens a real file; Miri isolates the filesystem")]
312 fn saving_and_loading_uses_the_file() {
313 let dir = std::env::temp_dir().join(format!("wbt-grants-{}", std::process::id()));
314 let store = GrantStore::new(dir.join("grants.txt"));
315 assert!(store.load().is_empty(), "nothing stored yet");
316
317 let mut devices = BTreeMap::new();
318 devices.insert(
319 "AA:BB:CC:DD:EE:FF".to_owned(),
320 stored(&[0x180F], &[], Some("Belt")),
321 );
322 store.save(&devices).expect("the store should be writable");
323
324 assert_eq!(store.load(), devices);
325
326 #[cfg(unix)]
327 {
328 use std::os::unix::fs::PermissionsExt;
329 let mode = std::fs::metadata(store.path())
330 .unwrap()
331 .permissions()
332 .mode();
333 assert_eq!(
334 mode & 0o777,
335 0o600,
336 "a permission store is not world-readable"
337 );
338 }
339 let _ = std::fs::remove_dir_all(&dir);
340 }
341
342 #[cfg(feature = "unrestricted")]
345 #[test]
346 fn a_wildcard_grant_survives_the_store() {
347 let mut devices = BTreeMap::new();
348 devices.insert(
349 "dev".to_owned(),
350 Stored {
351 name: Some("probe".to_owned()),
352 grant: Grant::unrestricted(),
353 },
354 );
355
356 let back = parse(&render(&devices));
357 let grant = &back.get("dev").unwrap().grant;
358 assert!(grant.permits_all_services());
359 assert!(grant.permits_all_manufacturer_data());
360 assert!(
361 grant.services.is_empty(),
362 "the wildcard is not a UUID and must not parse as one"
363 );
364 }
365
366 #[test]
370 fn a_wildcard_record_degrades_to_an_empty_grant() {
371 let text = format!("{HEADER}\ndev\tprobe\t*\t*\n");
372 let back = parse(&text);
373 let grant = &back.get("dev").unwrap().grant;
374
375 assert!(grant.services.is_empty());
376 assert!(grant.manufacturer_data.is_empty());
377 #[cfg(not(feature = "unrestricted"))]
378 {
379 assert!(!grant.permits_all_services());
380 assert!(!grant.permits(&BluetoothUuid::from_u16(0x180F)));
381 }
382 }
383}