Skip to main content

webbluetooth_core/
grants.rs

1//! Grants that outlive the process.
2//!
3//! The specification models a permission store, not a per-run set: a
4//! `BluetoothPermissionStorage` holds `allowedDevices`, `getDevices()` is
5//! defined as reading it, and `requestDevice` is defined as *adding* to it.
6//! That is what makes a page able to reconnect to something the user chose
7//! last week without asking again.
8//!
9//! Nothing here runs by default. `Bluetooth::new` keeps its grants in
10//! memory and loses them on exit, which is the safe thing for a program that
11//! did not ask for anything else. A caller that wants the specification's
12//! behaviour opts in with `Bluetooth::with_grants`.
13//!
14//! # What this file is
15//!
16//! The file *is* the permission. Anything that can write it can grant itself a
17//! device and every service on it, without a chooser and without the user
18//! being present — so it is created `0600`, and where you put it matters as
19//! much as anything in this crate. A world-writable directory is a way to hand
20//! out access to the user's heart-rate monitor.
21//!
22//! Losing it is harmless: an unreadable or corrupt store starts empty, which
23//! costs a trip through the chooser and nothing else. That is why every parse
24//! failure here is a skipped line rather than an error — a store that refuses
25//! to load because one line is malformed would lock a caller out of devices it
26//! legitimately owns.
27//!
28//! # Format
29//!
30//! One device per line, tab-separated, with a header naming the version:
31//!
32//! ```text
33//! # webbluetooth grants v1
34//! AA:BB:CC:DD:EE:FF<TAB>Heart Rate Belt<TAB>0000180d-…,0000180f-…<TAB>76
35//! ```
36//!
37//! `<TAB>` is a literal tab. Shown this way because a tab in a doc
38//! comment renders as ambiguous whitespace, and the separator being a
39//! tab rather than a space is the whole reason a device name needs no
40//! quoting.
41//!
42//! Plain text on purpose: a permission store you cannot read is one you cannot
43//! audit, and the first question anyone asks of it is "what does this grant?".
44
45use crate::registry::Grant;
46use crate::uuid::BluetoothUuid;
47use std::collections::BTreeMap;
48use std::path::{Path, PathBuf};
49
50/// The header, which is also the version marker.
51const HEADER: &str = "# webbluetooth grants v1";
52
53/// Stands in for "all of them" in the services and companies fields.
54///
55/// Chosen because it parses as neither a UUID nor a `u16`, so a build without
56/// the `unrestricted` feature reads a wildcard record as a grant of nothing.
57const WILDCARD: &str = "*";
58
59/// A grant as stored: what was allowed, and what the device was called.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct Stored {
62    /// The name the device had when it was granted.
63    pub name: Option<String>,
64    /// What it was granted access to.
65    pub grant: Grant,
66}
67
68/// Grants kept in a file.
69#[derive(Debug, Clone)]
70pub struct GrantStore {
71    path: PathBuf,
72}
73
74impl GrantStore {
75    /// A store backed by `path`, which need not exist yet.
76    pub fn new(path: impl Into<PathBuf>) -> Self {
77        Self { path: path.into() }
78    }
79
80    /// Where the grants are kept.
81    pub fn path(&self) -> &Path {
82        &self.path
83    }
84
85    /// Read every stored grant.
86    ///
87    /// An absent, unreadable or malformed store reads as empty rather than as
88    /// an error: the worst that costs is a trip through the chooser, whereas
89    /// refusing to start would lock a caller out of its own devices.
90    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    /// Write every grant, replacing what was there.
98    ///
99    /// Written to a temporary file and renamed, so an interrupted write leaves
100    /// the previous store intact rather than a half-written one. A permission
101    /// store truncated by a crash would silently revoke everything.
102    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/// `0600` — this file is a permission, and nobody else's business.
116#[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/// Windows inherits the directory's ACL, and there is no mode to set.
123#[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        // `*` is the wildcard grant, and is not a UUID or a company number —
133        // so a reader that predates the `unrestricted` feature drops it on the
134        // floor and ends up with a grant of nothing. That is the safe
135        // direction for a permission to degrade in.
136        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        // A tab-separated record, so a name with spaces in it needs no
152        // quoting; a name with a tab or newline in it is not representable and
153        // is trimmed rather than allowed to forge a second record.
154        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        // Only the line ending. `trim_end` would take the trailing tabs with
169        // it, and a device granted no services has nothing but trailing tabs —
170        // the record would lose its empty fields and stop parsing.
171        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; // Not a record; skip it rather than fail the store.
179        };
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                    // Without the feature there is nowhere to put it, so a
207                    // wildcard record reads back as the empty grant it already
208                    // parsed to above.
209                    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    /// A device granted nothing but the right to exist still round-trips.
237    ///
238    /// Its record is an id and three empty fields, so anything trimming
239    /// trailing whitespace eats the structure and the grant disappears.
240    #[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    /// A name is free text from a peer. It must not be able to forge a second
261    /// record and grant itself a device.
262    #[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        // And the surviving grant is still only what it was given.
280        let only = back.values().next().unwrap();
281        assert_eq!(only.grant.services.len(), 1);
282    }
283
284    /// A store that will not parse must not lock the caller out.
285    #[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        // A good line beside a bad one still loads.
291        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    /// An unparseable UUID is dropped rather than widening the grant.
298    #[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    /// Miri runs with filesystem isolation on, and this test is about the
307    /// filesystem. Pre-existing: it has been failing `./scripts/check.sh miri`
308    /// since it was written, because the crate it lived in was already in that
309    /// step. The parsing either side of the file is covered above, on strings.
310    #[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    /// A wildcard grant has to come back as one, or the next run of an explorer
343    /// silently sees nothing.
344    #[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    /// The `*` field is not a UUID and not a company number, so a build with no
367    /// `unrestricted` feature reads the record as a grant of nothing rather
368    /// than inheriting a permission it cannot represent.
369    #[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}