Skip to main content

webbluetooth_core/
registry.rs

1//! The device registry, shared by every backend.
2//!
3//! Each platform reaches a peripheral differently — a retained `CBPeripheral`,
4//! a D-Bus object path, a Bluetooth address and an ATT socket — but what is
5//! *remembered* about a granted device is the same everywhere: its name, the
6//! services the grant covers, whether the link is up, and which generation of
7//! handles is still valid.
8//!
9//! Keeping that here rather than three times over matters most for the two
10//! checks that enforce the security model. [`DeviceRegistry::check_allowed`] is
11//! what makes an unrequested service a `SecurityError`, and
12//! [`DeviceRegistry::check_generation`] is what stops a handle outliving the
13//! connection that produced it. A fix to either should not need finding in
14//! three files.
15
16use crate::error::{Error, Result};
17use crate::uuid::BluetoothUuid;
18use futures_channel::mpsc;
19use std::collections::{BTreeSet, HashMap};
20use std::sync::{Arc, Mutex};
21
22/// One granted device. `T` is whatever the backend needs to reach it.
23/// What `request_device` granted access to.
24///
25/// Both halves are permission, not preference: a service outside `services` is
26/// a `SecurityError`, and manufacturer data from a company outside
27/// `manufacturer_data` is withheld from advertisement events rather than
28/// reported. They travel together because they are granted together, in one
29/// call, and are meaningless apart from it.
30#[derive(Debug, Clone, Default, PartialEq, Eq)]
31pub struct Grant {
32    /// The services this grant permits. Anything else is refused, and the
33    /// blocklist overrides it.
34    pub services: BTreeSet<BluetoothUuid>,
35    /// Every service on the device, whatever `services` says.
36    ///
37    /// Outside the Web Bluetooth model, and behind the `unrestricted` feature
38    /// so that reaching for it is a decision somebody made in a manifest. It
39    /// exists for the one program an allowlist cannot serve: a general
40    /// explorer, which shows a device's custom 128-bit services and therefore
41    /// cannot name them in advance.
42    ///
43    /// The blocklist is not part of this and still applies. Read it through
44    /// [`Grant::permits_all_services`], which compiles either way.
45    #[cfg(feature = "unrestricted")]
46    pub all_services: bool,
47    /// Company identifiers whose advertisement data may be seen.
48    pub manufacturer_data: Vec<u16>,
49    /// Manufacturer data from every company, whatever `manufacturer_data` says.
50    ///
51    /// Gated as [`Self::all_services`] is, and read through
52    /// [`Grant::permits_all_manufacturer_data`]. The manufacturer blocklist is
53    /// not part of this either, and still applies.
54    #[cfg(feature = "unrestricted")]
55    pub all_manufacturer_data: bool,
56}
57
58impl Grant {
59    /// A grant of nothing: no service reachable, no manufacturer data seen.
60    ///
61    /// Build one up for [`Bluetooth::adopt_device`], which is granting access
62    /// rather than matching a device and so has no use for the filters a
63    /// `RequestDeviceOptions` also carries.
64    ///
65    /// [`Bluetooth::adopt_device`]: https://docs.rs/webbluetooth
66    pub fn new() -> Self {
67        Self::default()
68    }
69
70    /// Reach every service on the device — the explorer's grant.
71    ///
72    /// This is the deliberate hole in the allowlist, and the only thing in
73    /// this crate that opens one. Web Bluetooth's per-device allowlist exists
74    /// to stop a *page* learning more than the user agreed to; a program that
75    /// is itself the thing the user is operating — a BLE browser, a bring-up
76    /// tool — is on the other side of that boundary and has to enumerate what
77    /// it was never told about.
78    ///
79    /// The blocklist is unaffected: `get_primary_service` refuses a
80    /// blocklisted service under this grant exactly as under any other, and
81    /// blocklisted attributes stay filtered out of discovery.
82    #[cfg(feature = "unrestricted")]
83    pub fn all_services() -> Self {
84        Self {
85            all_services: true,
86            ..Self::default()
87        }
88    }
89
90    /// See manufacturer data from every company identifier.
91    ///
92    /// The manufacturer blocklist still applies, so an iBeacon frame is
93    /// withheld under this too — that one is not a permission.
94    #[cfg(feature = "unrestricted")]
95    pub fn all_manufacturer_data(mut self) -> Self {
96        self.all_manufacturer_data = true;
97        self
98    }
99
100    /// Every service and every company identifier: [`Self::all_services`] and
101    /// [`Self::all_manufacturer_data`] together.
102    #[cfg(feature = "unrestricted")]
103    pub fn unrestricted() -> Self {
104        Self::all_services().all_manufacturer_data()
105    }
106
107    /// Whether this grant reaches every service, rather than a named set.
108    ///
109    /// Always `false` without the `unrestricted` feature, so a caller checks
110    /// this without knowing whether the field exists.
111    pub fn permits_all_services(&self) -> bool {
112        #[cfg(feature = "unrestricted")]
113        {
114            self.all_services
115        }
116        #[cfg(not(feature = "unrestricted"))]
117        {
118            false
119        }
120    }
121
122    /// Whether this grant reaches every company identifier.
123    pub fn permits_all_manufacturer_data(&self) -> bool {
124        #[cfg(feature = "unrestricted")]
125        {
126            self.all_manufacturer_data
127        }
128        #[cfg(not(feature = "unrestricted"))]
129        {
130            false
131        }
132    }
133
134    /// Whether `uuid` is within this grant. The blocklist is a separate check
135    /// and overrides this one.
136    pub fn permits(&self, uuid: &BluetoothUuid) -> bool {
137        self.permits_all_services() || self.services.contains(uuid)
138    }
139
140    /// Whether `company`'s advertisement data is within this grant. The
141    /// manufacturer blocklist is a separate check and overrides this one.
142    pub fn permits_company(&self, company: u16) -> bool {
143        self.permits_all_manufacturer_data() || self.manufacturer_data.contains(&company)
144    }
145
146    /// Permit access to a service.
147    ///
148    /// Refuses a blocklisted service here rather than at first use. The
149    /// refusal is not new — `get_primary_service` enforces the blocklist
150    /// whatever the grant says — but a grant that cannot be exercised is worth
151    /// reporting when it is written, which is what
152    /// [`RequestDeviceOptions::validate`](crate::filter::RequestDeviceOptions::validate)
153    /// does for the other path.
154    pub fn service(mut self, uuid: impl crate::uuid::IntoUuid) -> crate::error::Result<Self> {
155        let uuid = uuid.into_uuid()?;
156        if crate::blocklist::is_blocked(&uuid) {
157            return Err(crate::error::Error::Security(format!(
158                "service {uuid} is on the GATT blocklist"
159            )));
160        }
161        self.services.insert(uuid);
162        Ok(self)
163    }
164
165    /// Permit access to several services at once.
166    pub fn services<U: crate::uuid::IntoUuid>(
167        mut self,
168        uuids: impl IntoIterator<Item = U>,
169    ) -> crate::error::Result<Self> {
170        for uuid in uuids {
171            self = self.service(uuid)?;
172        }
173        Ok(self)
174    }
175
176    /// Permit reading advertisement data from these company identifiers.
177    pub fn manufacturer_data(mut self, ids: impl IntoIterator<Item = u16>) -> Self {
178        for company in ids {
179            if !self.manufacturer_data.contains(&company) {
180                self.manufacturer_data.push(company);
181            }
182        }
183        self
184    }
185
186    /// Refuse a grant that names something the blocklist forbids.
187    ///
188    /// The check that matters happens at use — `get_primary_service` consults
189    /// the blocklist whatever the grant says — so this is about reporting:
190    /// a grant built from a `RequestDeviceOptions` has been through
191    /// [`RequestDeviceOptions::validate`](crate::filter::RequestDeviceOptions::validate),
192    /// and one built by hand should not be held to a lower standard.
193    pub fn validate(&self) -> crate::error::Result<()> {
194        for uuid in &self.services {
195            if crate::blocklist::is_blocked(uuid) {
196                return Err(crate::error::Error::Security(format!(
197                    "service {uuid} is on the GATT blocklist"
198                )));
199            }
200        }
201        Ok(())
202    }
203
204    /// Everything either grant allows.
205    ///
206    /// A permission only ever widens: the specification unions a new request
207    /// with what was already allowed, so asking for less the second time does
208    /// not revoke anything.
209    pub fn union(&self, other: &Self) -> Self {
210        let mut manufacturer_data = self.manufacturer_data.clone();
211        for company in &other.manufacturer_data {
212            if !manufacturer_data.contains(company) {
213                manufacturer_data.push(*company);
214            }
215        }
216        Self {
217            services: self.services.union(&other.services).cloned().collect(),
218            #[cfg(feature = "unrestricted")]
219            all_services: self.all_services || other.all_services,
220            manufacturer_data,
221            #[cfg(feature = "unrestricted")]
222            all_manufacturer_data: self.all_manufacturer_data || other.all_manufacturer_data,
223        }
224    }
225}
226
227impl From<BTreeSet<BluetoothUuid>> for Grant {
228    /// A grant of services alone, which is what state restoration carries:
229    /// the specification's grant does not survive process death, so a restored
230    /// session is given the allowlist the caller declared up front and no
231    /// manufacturer data at all.
232    fn from(services: BTreeSet<BluetoothUuid>) -> Self {
233        let mut grant = Self::new();
234        grant.services = services;
235        grant
236    }
237}
238
239/// The services a device's grant reaches, as something answerable.
240///
241/// Discovery returns whatever the device has, and the caller has to drop what
242/// the grant does not cover. Nearly always that is a set membership test —
243/// but a wildcard grant —
244#[cfg_attr(feature = "unrestricted", doc = "[`Grant::all_services`],")]
245#[cfg_attr(not(feature = "unrestricted"), doc = "`Grant::all_services`,")]
246/// under the `unrestricted` feature — covers services whose UUIDs nobody knew
247/// to put in a set, and the test still has to come out `true`.
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub enum AllowedServices {
250    /// Every service on the device. The blocklist still applies on top.
251    All,
252    /// Only these, which is what `request_device` grants.
253    Only(BTreeSet<BluetoothUuid>),
254}
255
256impl AllowedServices {
257    /// Whether `uuid` is covered.
258    pub fn contains(&self, uuid: &BluetoothUuid) -> bool {
259        match self {
260            Self::All => true,
261            Self::Only(set) => set.contains(uuid),
262        }
263    }
264
265    /// Whether this covers every service, rather than a named set.
266    pub fn is_all(&self) -> bool {
267        matches!(self, Self::All)
268    }
269
270    /// The named services, or `None` when every service is covered.
271    ///
272    /// For a caller that wants to *list* the allowlist rather than test
273    /// against it — printing a grant, say.
274    pub fn named(&self) -> Option<&BTreeSet<BluetoothUuid>> {
275        match self {
276            Self::All => None,
277            Self::Only(set) => Some(set),
278        }
279    }
280}
281
282/// One granted device, and whatever the backend keeps beside it.
283pub struct Device<T> {
284    /// Its name, if the platform reported one.
285    pub name: Option<String>,
286    /// What `request_device` granted. Reaching anything else is a
287    /// `SecurityError`, as in a browser.
288    pub allowed: Grant,
289    /// Whether the backend believes the link is up.
290    pub connected: bool,
291    /// Bumped whenever every handle into this device becomes stale.
292    pub generation: u64,
293    /// Serialises GATT operations, as the spec's per-device queue does.
294    ///
295    /// Unused on the web, where the browser runs that queue itself.
296    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
297    pub gatt: Arc<futures_util::lock::Mutex<()>>,
298    /// Whatever the backend needs to reach the device. The web backend needs
299    /// nothing: the browser holds the device and this side holds only its id.
300    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
301    pub inner: T,
302}
303
304/// Every device this session has been granted, and what it may reach.
305///
306/// Shared by all six backends: the allowlist, the generation counter that
307/// invalidates stale handles, and the disconnect and service-changed watchers
308/// are the same problem everywhere.
309pub struct DeviceRegistry<T> {
310    devices: Mutex<HashMap<String, Device<T>>>,
311    listeners: Mutex<HashMap<String, Vec<mpsc::UnboundedSender<()>>>>,
312    /// Watchers of the service set, kept apart from the disconnect watchers so
313    /// a device that reconnects and re-discovers does not look like a drop.
314    service_listeners: Mutex<HashMap<String, Vec<mpsc::UnboundedSender<()>>>>,
315}
316
317impl<T> Default for DeviceRegistry<T> {
318    fn default() -> Self {
319        Self {
320            devices: Mutex::new(HashMap::new()),
321            listeners: Mutex::new(HashMap::new()),
322            service_listeners: Mutex::new(HashMap::new()),
323        }
324    }
325}
326
327impl<T> DeviceRegistry<T> {
328    /// Grant access to a device.
329    /// Record a grant, merging it with anything this device was already
330    /// granted.
331    ///
332    /// Merging, not replacing, because that is what the specification says:
333    /// *"add the contents of `allowedDevice.allowedServices` to
334    /// `grantedServiceUUIDs`"*. A second `requestDevice` for the same device
335    /// with narrower options must not take away what the first one granted —
336    /// a caller still holding a service from the earlier grant would start
337    /// getting `SecurityError` for something it was legitimately given.
338    ///
339    /// The generation is carried forward for a harder reason. It counts how
340    /// many times every handle into this device became stale, and
341    /// `check_generation` compares a handle's copy against it. Resetting it to
342    /// zero would let a handle captured before a disconnect match again
343    /// afterwards, so a re-grant would quietly revive objects that point at
344    /// attributes the peer may have rearranged. It only ever goes forwards.
345    pub fn insert(
346        &self,
347        id: &str,
348        name: Option<String>,
349        allowed: Grant,
350        connected: bool,
351        inner: T,
352    ) {
353        let mut devices = self.devices.lock().unwrap();
354        let previous = devices.get(id);
355        let generation = previous.map(|d| d.generation).unwrap_or(0);
356        // The lock is kept too: a fresh one would let an operation already in
357        // flight run beside the next, which is the thing it exists to prevent.
358        let gatt = previous
359            .map(|d| d.gatt.clone())
360            .unwrap_or_else(|| Arc::new(futures_util::lock::Mutex::new(())));
361        let allowed = match previous {
362            Some(d) => d.allowed.union(&allowed),
363            None => allowed,
364        };
365
366        devices.insert(
367            id.to_owned(),
368            Device {
369                name,
370                allowed,
371                connected,
372                generation,
373                gatt,
374                inner,
375            },
376        );
377    }
378
379    /// Read something out of a device's record.
380    pub fn get<R>(&self, id: &str, f: impl FnOnce(&Device<T>) -> R) -> Result<R> {
381        let devices = self.devices.lock().unwrap();
382        let device = devices
383            .get(id)
384            .ok_or_else(|| Error::InvalidState(format!("device {id} is no longer known")))?;
385        Ok(f(device))
386    }
387
388    /// Modify a device's record. Silently does nothing if it is gone.
389    pub fn update(&self, id: &str, f: impl FnOnce(&mut Device<T>)) {
390        if let Some(device) = self.devices.lock().unwrap().get_mut(id) {
391            f(device);
392        }
393    }
394
395    /// Find a device by something only the backend can recognise — a peripheral
396    /// pointer, an object path — and modify it.
397    ///
398    /// Only the Apple backend needs this: its events carry a `CBPeripheral`
399    /// rather than an id, so the device has to be found by identity.
400    #[cfg_attr(not(target_vendor = "apple"), allow(dead_code))]
401    pub fn update_where(
402        &self,
403        matches: impl Fn(&Device<T>) -> bool,
404        f: impl FnOnce(&mut Device<T>),
405    ) -> Option<String> {
406        let mut devices = self.devices.lock().unwrap();
407        let found = devices.iter_mut().find(|(_, d)| matches(d));
408        let (id, device) = found?;
409        let id = id.clone();
410        f(device);
411        Some(id)
412    }
413
414    /// The id of a device matching a backend-specific predicate.
415    ///
416    /// Unused where a backend's events already carry the device id rather than
417    /// a platform handle — `linux-hci`, Windows and the web all do.
418    #[cfg_attr(
419        any(
420            all(target_os = "linux", feature = "linux-hci"),
421            target_os = "windows",
422            target_arch = "wasm32",
423        ),
424        allow(dead_code)
425    )]
426    pub fn find(&self, matches: impl Fn(&Device<T>) -> bool) -> Option<String> {
427        self.devices
428            .lock()
429            .unwrap()
430            .iter()
431            .find(|(_, d)| matches(d))
432            .map(|(id, _)| id.clone())
433    }
434
435    /// The device's name, if it has one.
436    pub fn name(&self, id: &str) -> Option<String> {
437        self.get(id, |d| d.name.clone()).ok().flatten()
438    }
439
440    /// Whether the device is recorded as connected.
441    pub fn is_connected(&self, id: &str) -> bool {
442        self.get(id, |d| d.connected).unwrap_or(false)
443    }
444
445    /// The device's current generation, which a handle records when minted.
446    pub fn generation(&self, id: &str) -> Result<u64> {
447        self.get(id, |d| d.generation)
448    }
449
450    /// Every granted device's id.
451    pub fn ids(&self) -> Vec<String> {
452        self.devices.lock().unwrap().keys().cloned().collect()
453    }
454
455    /// Revoke a grant, returning the record so the backend can tear down its
456    /// side of it.
457    pub fn remove(&self, id: &str) -> Option<Device<T>> {
458        self.listeners.lock().unwrap().remove(id);
459        self.devices.lock().unwrap().remove(id)
460    }
461
462    /// The per-device allowlist from `request_device`.
463    pub fn check_allowed(&self, id: &str, uuid: &BluetoothUuid) -> Result<()> {
464        if self.get(id, |d| d.allowed.permits(uuid))? {
465            Ok(())
466        } else {
467            Err(Error::Security(format!(
468                "service {uuid} was not requested — list it in filters or optional_services"
469            )))
470        }
471    }
472
473    /// What this device was granted access to.
474    ///
475    /// A set is not enough on its own: a grant can name every service rather
476    /// than a list of them, and a caller handed a set has no way to say so —
477    /// it would filter discovery down to the empty set and report a device
478    /// with nothing on it. [`AllowedServices`] answers `contains` for both
479    /// shapes, so the filtering call sites cannot get this wrong.
480    pub fn allowed_services(&self, id: &str) -> Result<AllowedServices> {
481        self.get(id, |d| {
482            if d.allowed.permits_all_services() {
483                AllowedServices::All
484            } else {
485                AllowedServices::Only(d.allowed.services.clone())
486            }
487        })
488    }
489
490    /// The company identifiers this device's grant covers.
491    ///
492    /// Empty means none were asked for, which is the common case and means no
493    /// manufacturer data is reported at all.
494    /// Everything `id` was granted, or an empty grant if it is not known.
495    ///
496    /// An unknown device getting an empty grant rather than a full one is the
497    /// safe direction: it reports nothing rather than everything.
498    pub fn grant(&self, id: &str) -> Grant {
499        self.get(id, |d| d.allowed.clone()).unwrap_or_default()
500    }
501
502    /// Fail if handles minted at `generation` are stale, or the link is down.
503    /// Whether a handle taken at `generation` may still be used on `id`.
504    ///
505    /// The two failures are distinct, and the specification orders them: it
506    /// checks `gatt.connected` before it checks whether the object still
507    /// represents anything. The distinction is worth keeping because it tells
508    /// the caller what to do about it — a disconnection is something to
509    /// reconnect from and retry, whereas a stale handle survives reconnecting
510    /// and has to be rediscovered. Collapsing them into one error loses that.
511    pub fn check_generation(&self, id: &str, generation: u64) -> Result<()> {
512        // An id nobody has heard of is a stale object, not a lost connection,
513        // so this comes first.
514        let current = self.generation(id)?;
515        if !self.is_connected(id) {
516            return Err(Error::Network("the device is not connected".into()));
517        }
518        if current != generation {
519            return Err(Error::InvalidState(
520                "this GATT object is stale — the device disconnected or changed its services"
521                    .into(),
522            ));
523        }
524        Ok(())
525    }
526
527    /// Take this device's GATT lock, held across one operation.
528    ///
529    /// Unused on the web: `navigator.bluetooth` serialises GATT operations
530    /// itself, so taking a second lock here would only add contention.
531    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
532    pub async fn gatt_lock(&self, id: &str) -> Result<futures_util::lock::OwnedMutexGuard<()>> {
533        Ok(self.get(id, |d| d.gatt.clone())?.lock_owned().await)
534    }
535
536    /// Watch for this device's service set changing — the specification's
537    /// `serviceadded`, `servicechanged` and `serviceremoved` between them.
538    ///
539    /// One signal rather than three, because that is what the platforms give:
540    /// each reports that the set changed and that existing handles are stale,
541    /// not which service it was. Inventing the distinction would mean
542    /// reporting detail nobody actually has.
543    pub fn watch_services_changed(&self, id: &str) -> mpsc::UnboundedReceiver<()> {
544        let (tx, rx) = mpsc::unbounded();
545        self.service_listeners
546            .lock()
547            .unwrap()
548            .entry(id.to_owned())
549            .or_default()
550            .push(tx);
551        rx
552    }
553
554    /// The service set changed: invalidate every handle into the device and
555    /// tell anyone watching.
556    ///
557    /// Only the platforms that detect it call this — CoreBluetooth's
558    /// `didModifyServices:` and Android's `onServiceChanged`. BlueZ, WinRT and
559    /// a raw ATT socket give no such signal, so on those targets this is
560    /// compiled and never reached; `watch_services_changed` there returns a
561    /// stream that stays silent rather than one that does not exist.
562    /// Every handle into this device is now stale, but the link is still up.
563    ///
564    /// Called by every backend, each from whatever its platform calls this:
565    /// CoreBluetooth's `didModifyServices:`, Android's `onServiceChanged`,
566    /// BlueZ's GATT objects appearing and vanishing, WinRT's
567    /// `GattServicesChanged`, the browser's `serviceschanged`, and — for
568    /// `linux-hci`, which has no stack to inherit it from — an indication on
569    /// the peer's own Service Changed characteristic.
570    pub fn mark_services_changed(&self, id: &str) {
571        self.update(id, |d| d.generation += 1);
572        let mut listeners = self.service_listeners.lock().unwrap();
573        if let Some(subscribers) = listeners.get_mut(id) {
574            subscribers.retain(|tx| tx.unbounded_send(()).is_ok());
575        }
576    }
577
578    /// A stream that yields once each time the device disconnects.
579    pub fn watch_disconnect(&self, id: &str) -> mpsc::UnboundedReceiver<()> {
580        let (tx, rx) = mpsc::unbounded();
581        self.listeners
582            .lock()
583            .unwrap()
584            .entry(id.to_owned())
585            .or_default()
586            .push(tx);
587        rx
588    }
589
590    /// Mark a device disconnected: drop the link, invalidate every handle into
591    /// it, and tell anyone watching.
592    pub fn mark_disconnected(&self, id: &str) {
593        self.update(id, |d| {
594            d.connected = false;
595            d.generation += 1;
596        });
597        let mut listeners = self.listeners.lock().unwrap();
598        if let Some(subscribers) = listeners.get_mut(id) {
599            subscribers.retain(|tx| tx.unbounded_send(()).is_ok());
600            if subscribers.is_empty() {
601                listeners.remove(id);
602            }
603        }
604    }
605}
606
607/// The methods every backend forwards to its registry, unchanged.
608///
609/// Ten one-line functions, written out six times, byte for byte — the backends
610/// differ in how they reach a radio and not at all in how they answer "is this
611/// device connected". Expanded inside each `impl Inner` rather than put behind
612/// a trait: exactly one backend is compiled into any build, so a trait would
613/// buy dynamic dispatch nobody needs, which is the same reasoning that keeps
614/// `Inner` a concrete type.
615///
616/// Every type is named absolutely, so this does not depend on which of them a
617/// given backend happens to have imported.
618#[macro_export]
619macro_rules! forward_to_registry {
620    () => {
621        pub fn device_name(&self, id: &str) -> Option<String> {
622            self.devices.name(id)
623        }
624
625        pub fn is_connected(&self, id: &str) -> bool {
626            self.devices.is_connected(id)
627        }
628
629        pub fn generation(&self, id: &str) -> $crate::error::Result<u64> {
630            self.devices.generation(id)
631        }
632
633        pub fn granted_devices(&self) -> Vec<String> {
634            self.devices.ids()
635        }
636
637        pub fn check_allowed(
638            &self,
639            id: &str,
640            uuid: &$crate::uuid::BluetoothUuid,
641        ) -> $crate::error::Result<()> {
642            self.devices.check_allowed(id, uuid)
643        }
644
645        pub fn allowed_services(
646            &self,
647            id: &str,
648        ) -> $crate::error::Result<$crate::registry::AllowedServices> {
649            self.devices.allowed_services(id)
650        }
651
652        pub fn check_generation(&self, id: &str, generation: u64) -> $crate::error::Result<()> {
653            self.devices.check_generation(id, generation)
654        }
655
656        pub fn watch_disconnect(
657            &self,
658            id: &str,
659        ) -> $crate::futures_channel::mpsc::UnboundedReceiver<()> {
660            self.devices.watch_disconnect(id)
661        }
662
663        pub fn watch_services_changed(
664            &self,
665            id: &str,
666        ) -> $crate::futures_channel::mpsc::UnboundedReceiver<()> {
667            self.devices.watch_services_changed(id)
668        }
669
670        pub fn grant(&self, id: &str) -> $crate::registry::Grant {
671            self.devices.grant(id)
672        }
673    };
674}
675
676pub use crate::forward_to_registry;
677
678#[cfg(test)]
679mod tests {
680    use super::*;
681    use crate::uuid::services;
682    use futures_executor::block_on;
683
684    /// A grant of exactly these services and company identifiers.
685    ///
686    /// Built by assignment rather than as a struct literal: `Grant` carries two
687    /// more fields under the `unrestricted` feature and neither without it, so
688    /// a literal is either incomplete or redundant depending on how the crate
689    /// was compiled.
690    fn grant_of(services: &[BluetoothUuid], companies: &[u16]) -> Grant {
691        let mut grant = Grant::new();
692        grant.services = services.iter().copied().collect();
693        grant.manufacturer_data = companies.to_vec();
694        grant
695    }
696
697    fn registry() -> DeviceRegistry<u32> {
698        let registry = DeviceRegistry::default();
699        registry.insert(
700            "AA:BB",
701            Some("Sensor".into()),
702            BTreeSet::from([services::HEART_RATE]).into(),
703            true,
704            7u32,
705        );
706        registry
707    }
708
709    #[test]
710    fn an_unrequested_service_is_a_security_error() {
711        let registry = registry();
712        assert!(registry
713            .check_allowed("AA:BB", &services::HEART_RATE)
714            .is_ok());
715        let refused = registry.check_allowed("AA:BB", &services::BATTERY_SERVICE);
716        assert!(
717            matches!(refused, Err(Error::Security(_))),
718            "got {refused:?}"
719        );
720    }
721
722    #[test]
723    fn handles_go_stale_when_the_generation_moves() {
724        let registry = registry();
725        assert!(registry.check_generation("AA:BB", 0).is_ok());
726
727        registry.mark_disconnected("AA:BB");
728
729        // Both reasons now apply, and the specification orders them: being
730        // disconnected is reported ahead of the handle being stale, because
731        // reconnecting is what the caller has to do first either way.
732        assert!(matches!(
733            registry.check_generation("AA:BB", 0),
734            Err(Error::Network(_))
735        ));
736        assert!(matches!(
737            registry.check_generation("AA:BB", 1),
738            Err(Error::Network(_))
739        ));
740        assert!(!registry.is_connected("AA:BB"));
741    }
742
743    /// Reconnecting clears the disconnection but not the staleness: handles
744    /// taken before it have to be rediscovered, and say so.
745    #[test]
746    fn a_handle_from_before_a_reconnect_is_stale_not_disconnected() {
747        let registry = registry();
748        let before = registry.generation("AA:BB").unwrap();
749
750        registry.mark_disconnected("AA:BB");
751        registry.update("AA:BB", |d| d.connected = true);
752
753        assert!(matches!(
754            registry.check_generation("AA:BB", before),
755            Err(Error::InvalidState(_))
756        ));
757        let now = registry.generation("AA:BB").unwrap();
758        assert!(registry.check_generation("AA:BB", now).is_ok());
759    }
760
761    #[test]
762    fn disconnecting_notifies_watchers() {
763        let registry = registry();
764        let mut watcher = registry.watch_disconnect("AA:BB");
765        registry.mark_disconnected("AA:BB");
766        assert!(block_on(futures_util::StreamExt::next(&mut watcher)).is_some());
767    }
768
769    #[test]
770    fn an_unknown_device_is_an_invalid_state_not_a_panic() {
771        let registry: DeviceRegistry<u32> = DeviceRegistry::default();
772        assert!(matches!(
773            registry.generation("nope"),
774            Err(Error::InvalidState(_))
775        ));
776        assert!(matches!(
777            registry.check_generation("nope", 0),
778            Err(Error::InvalidState(_))
779        ));
780        assert!(registry.name("nope").is_none());
781        assert!(!registry.is_connected("nope"));
782    }
783
784    #[test]
785    fn the_gatt_lock_serialises_operations() {
786        let registry = registry();
787        block_on(async {
788            let first = registry.gatt_lock("AA:BB").await.unwrap();
789            // A second attempt must not be ready while the first is held.
790            let second = registry.gatt_lock("AA:BB");
791            let pending = futures_util::poll!(std::pin::pin!(second));
792            assert!(pending.is_pending(), "the lock let two operations through");
793            drop(first);
794        });
795    }
796
797    #[test]
798    fn devices_can_be_found_by_backend_specific_identity() {
799        let registry = registry();
800        // A backend looks its own payload up — a pointer, a path, an address.
801        assert_eq!(registry.find(|d| d.inner == 7), Some("AA:BB".into()));
802        assert_eq!(registry.find(|d| d.inner == 99), None);
803
804        registry.update_where(|d| d.inner == 7, |d| d.name = Some("Renamed".into()));
805        assert_eq!(registry.name("AA:BB").as_deref(), Some("Renamed"));
806    }
807
808    /// A second `requestDevice` for the same device must not take away what
809    /// the first one granted.
810    ///
811    /// The specification unions: *"add the contents of
812    /// `allowedDevice.allowedServices` to `grantedServiceUUIDs`"*. Replacing
813    /// instead would revoke a service silently — a caller still holding it
814    /// starts getting `SecurityError` for something it was given.
815    #[test]
816    fn a_narrower_second_grant_does_not_revoke_the_first() {
817        let registry = DeviceRegistry::<()>::default();
818        let battery = BluetoothUuid::from_u16(0x180F);
819        let info = BluetoothUuid::from_u16(0x180A);
820
821        registry.insert(
822            "dev",
823            None,
824            grant_of(&[battery, info], &[0x004C]),
825            false,
826            (),
827        );
828        // The same device again, asking for less.
829        registry.insert("dev", None, grant_of(&[battery], &[]), false, ());
830
831        assert!(
832            registry.check_allowed("dev", &info).is_ok(),
833            "the first grant's service is still allowed"
834        );
835        assert!(registry.check_allowed("dev", &battery).is_ok());
836        assert_eq!(
837            registry.grant("dev").manufacturer_data,
838            vec![0x004C],
839            "and so is the company it was granted"
840        );
841    }
842
843    /// A re-grant must not revive handles that went stale.
844    ///
845    /// `generation` counts how many times every handle into a device became
846    /// invalid. A handle carries the value it was made at, and
847    /// `check_generation` compares them. If a re-grant reset the counter, a
848    /// handle captured before a disconnect would match again afterwards and be
849    /// treated as live — pointing at attributes the peer is free to have
850    /// rearranged while it was away.
851    #[test]
852    fn a_re_grant_does_not_revive_stale_handles() {
853        let registry = DeviceRegistry::<()>::default();
854        let grant = || grant_of(&[BluetoothUuid::from_u16(0x180F)], &[]);
855
856        registry.insert("dev", None, grant(), true, ());
857        let captured = registry.generation("dev").unwrap();
858        assert!(registry.check_generation("dev", captured).is_ok());
859
860        // The link drops: everything handed out before is now stale.
861        registry.mark_disconnected("dev");
862
863        // The device is granted again and reconnects.
864        registry.insert("dev", None, grant(), true, ());
865        assert_eq!(
866            registry
867                .check_generation("dev", captured)
868                .unwrap_err()
869                .to_string(),
870            Error::InvalidState(
871                "this GATT object is stale — the device disconnected or changed its services"
872                    .into()
873            )
874            .to_string(),
875            "the handle from before the disconnect must stay stale"
876        );
877        // And a handle made now is fine.
878        let fresh = registry.generation("dev").unwrap();
879        assert!(registry.check_generation("dev", fresh).is_ok());
880    }
881
882    #[test]
883    fn forgetting_removes_the_grant_and_its_watchers() {
884        let registry = registry();
885        let _watcher = registry.watch_disconnect("AA:BB");
886        assert!(registry.remove("AA:BB").is_some());
887        assert!(registry.ids().is_empty());
888        assert!(registry.remove("AA:BB").is_none());
889    }
890
891    /// The point of the escape hatch: a service the grant could not have named,
892    /// because a 128-bit vendor UUID is not knowable before the device is read.
893    #[cfg(feature = "unrestricted")]
894    #[test]
895    fn an_unrestricted_grant_reaches_a_service_nobody_named() {
896        let registry = DeviceRegistry::<()>::default();
897        let vendor = BluetoothUuid::parse("f000aa00-0451-4000-b000-000000000000").unwrap();
898
899        registry.insert("dev", None, Grant::unrestricted(), false, ());
900
901        assert!(registry.check_allowed("dev", &vendor).is_ok());
902        assert!(registry.allowed_services("dev").unwrap().is_all());
903        assert!(registry.allowed_services("dev").unwrap().contains(&vendor));
904        // It is a wildcard, not a set, so there is no list to hand back.
905        assert!(registry.allowed_services("dev").unwrap().named().is_none());
906    }
907
908    /// Widening is the only direction a permission moves, and the flag is part
909    /// of the permission.
910    #[cfg(feature = "unrestricted")]
911    #[test]
912    fn a_wildcard_survives_a_narrower_re_grant() {
913        let narrow = Grant::new()
914            .service(BluetoothUuid::from_u16(0x180F))
915            .unwrap();
916
917        assert!(Grant::unrestricted().union(&narrow).permits_all_services());
918        assert!(narrow.union(&Grant::unrestricted()).permits_all_services());
919        assert!(!narrow.union(&narrow).permits_all_services());
920    }
921
922    /// The hatch opens the allowlist and nothing else.
923    #[cfg(feature = "unrestricted")]
924    #[test]
925    fn an_unrestricted_grant_is_still_subject_to_the_blocklist() {
926        // HID — the first entry in the vendored registry, and the reason the
927        // blocklist exists: reaching it would make a keylogger.
928        let hid = BluetoothUuid::from_u16(0x1812);
929        assert!(
930            crate::blocklist::is_blocked(&hid),
931            "the vendored blocklist must still block HID"
932        );
933
934        // The grant says yes, because a wildcard says yes to everything...
935        assert!(Grant::unrestricted().permits(&hid));
936        // ...and the blocklist, which is not a permission, still says no. The
937        // two checks are separate everywhere a service is reached:
938        // `get_primary_service` guards on the blocklist before the grant, and
939        // `get_primary_services` drops blocklisted attributes from discovery.
940        assert!(crate::blocklist::is_blocked(&hid));
941    }
942
943    /// Without the feature there is no way to express it, and the default is
944    /// the allowlist it always was.
945    #[test]
946    fn a_plain_grant_permits_only_what_it_names() {
947        let battery = BluetoothUuid::from_u16(0x180F);
948        let grant = Grant::new().service(battery).unwrap();
949
950        assert!(grant.permits(&battery));
951        assert!(!grant.permits(&BluetoothUuid::from_u16(0x180A)));
952        assert!(!grant.permits_all_services());
953        assert!(!grant.permits_all_manufacturer_data());
954        assert!(!Grant::default().permits(&battery));
955    }
956}