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 /// Company identifiers whose advertisement data may be seen.
36 pub manufacturer_data: Vec<u16>,
37}
38
39impl Grant {
40 /// A grant of nothing: no service reachable, no manufacturer data seen.
41 ///
42 /// Build one up for [`Bluetooth::adopt_device`], which is granting access
43 /// rather than matching a device and so has no use for the filters a
44 /// `RequestDeviceOptions` also carries.
45 ///
46 /// [`Bluetooth::adopt_device`]: https://docs.rs/webbluetooth
47 pub fn new() -> Self {
48 Self::default()
49 }
50
51 /// Permit access to a service.
52 ///
53 /// Refuses a blocklisted service here rather than at first use. The
54 /// refusal is not new — `get_primary_service` enforces the blocklist
55 /// whatever the grant says — but a grant that cannot be exercised is worth
56 /// reporting when it is written, which is what
57 /// [`RequestDeviceOptions::validate`](crate::filter::RequestDeviceOptions::validate)
58 /// does for the other path.
59 pub fn service(mut self, uuid: impl crate::uuid::IntoUuid) -> crate::error::Result<Self> {
60 let uuid = uuid.into_uuid()?;
61 if crate::blocklist::is_blocked(&uuid) {
62 return Err(crate::error::Error::Security(format!(
63 "service {uuid} is on the GATT blocklist"
64 )));
65 }
66 self.services.insert(uuid);
67 Ok(self)
68 }
69
70 /// Permit access to several services at once.
71 pub fn services<U: crate::uuid::IntoUuid>(
72 mut self,
73 uuids: impl IntoIterator<Item = U>,
74 ) -> crate::error::Result<Self> {
75 for uuid in uuids {
76 self = self.service(uuid)?;
77 }
78 Ok(self)
79 }
80
81 /// Permit reading advertisement data from these company identifiers.
82 pub fn manufacturer_data(mut self, ids: impl IntoIterator<Item = u16>) -> Self {
83 for company in ids {
84 if !self.manufacturer_data.contains(&company) {
85 self.manufacturer_data.push(company);
86 }
87 }
88 self
89 }
90
91 /// Refuse a grant that names something the blocklist forbids.
92 ///
93 /// The check that matters happens at use — `get_primary_service` consults
94 /// the blocklist whatever the grant says — so this is about reporting:
95 /// a grant built from a `RequestDeviceOptions` has been through
96 /// [`RequestDeviceOptions::validate`](crate::filter::RequestDeviceOptions::validate),
97 /// and one built by hand should not be held to a lower standard.
98 pub fn validate(&self) -> crate::error::Result<()> {
99 for uuid in &self.services {
100 if crate::blocklist::is_blocked(uuid) {
101 return Err(crate::error::Error::Security(format!(
102 "service {uuid} is on the GATT blocklist"
103 )));
104 }
105 }
106 Ok(())
107 }
108
109 /// Everything either grant allows.
110 ///
111 /// A permission only ever widens: the specification unions a new request
112 /// with what was already allowed, so asking for less the second time does
113 /// not revoke anything.
114 pub fn union(&self, other: &Self) -> Self {
115 let mut manufacturer_data = self.manufacturer_data.clone();
116 for company in &other.manufacturer_data {
117 if !manufacturer_data.contains(company) {
118 manufacturer_data.push(*company);
119 }
120 }
121 Self {
122 services: self.services.union(&other.services).cloned().collect(),
123 manufacturer_data,
124 }
125 }
126}
127
128impl From<BTreeSet<BluetoothUuid>> for Grant {
129 /// A grant of services alone, which is what state restoration carries:
130 /// the specification's grant does not survive process death, so a restored
131 /// session is given the allowlist the caller declared up front and no
132 /// manufacturer data at all.
133 fn from(services: BTreeSet<BluetoothUuid>) -> Self {
134 Self {
135 services,
136 manufacturer_data: Vec::new(),
137 }
138 }
139}
140
141/// One granted device, and whatever the backend keeps beside it.
142pub struct Device<T> {
143 /// Its name, if the platform reported one.
144 pub name: Option<String>,
145 /// What `request_device` granted. Reaching anything else is a
146 /// `SecurityError`, as in a browser.
147 pub allowed: Grant,
148 /// Whether the backend believes the link is up.
149 pub connected: bool,
150 /// Bumped whenever every handle into this device becomes stale.
151 pub generation: u64,
152 /// Serialises GATT operations, as the spec's per-device queue does.
153 ///
154 /// Unused on the web, where the browser runs that queue itself.
155 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
156 pub gatt: Arc<futures_util::lock::Mutex<()>>,
157 /// Whatever the backend needs to reach the device. The web backend needs
158 /// nothing: the browser holds the device and this side holds only its id.
159 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
160 pub inner: T,
161}
162
163/// Every device this session has been granted, and what it may reach.
164///
165/// Shared by all six backends: the allowlist, the generation counter that
166/// invalidates stale handles, and the disconnect and service-changed watchers
167/// are the same problem everywhere.
168pub struct DeviceRegistry<T> {
169 devices: Mutex<HashMap<String, Device<T>>>,
170 listeners: Mutex<HashMap<String, Vec<mpsc::UnboundedSender<()>>>>,
171 /// Watchers of the service set, kept apart from the disconnect watchers so
172 /// a device that reconnects and re-discovers does not look like a drop.
173 service_listeners: Mutex<HashMap<String, Vec<mpsc::UnboundedSender<()>>>>,
174}
175
176impl<T> Default for DeviceRegistry<T> {
177 fn default() -> Self {
178 Self {
179 devices: Mutex::new(HashMap::new()),
180 listeners: Mutex::new(HashMap::new()),
181 service_listeners: Mutex::new(HashMap::new()),
182 }
183 }
184}
185
186impl<T> DeviceRegistry<T> {
187 /// Grant access to a device.
188 /// Record a grant, merging it with anything this device was already
189 /// granted.
190 ///
191 /// Merging, not replacing, because that is what the specification says:
192 /// *"add the contents of `allowedDevice.allowedServices` to
193 /// `grantedServiceUUIDs`"*. A second `requestDevice` for the same device
194 /// with narrower options must not take away what the first one granted —
195 /// a caller still holding a service from the earlier grant would start
196 /// getting `SecurityError` for something it was legitimately given.
197 ///
198 /// The generation is carried forward for a harder reason. It counts how
199 /// many times every handle into this device became stale, and
200 /// `check_generation` compares a handle's copy against it. Resetting it to
201 /// zero would let a handle captured before a disconnect match again
202 /// afterwards, so a re-grant would quietly revive objects that point at
203 /// attributes the peer may have rearranged. It only ever goes forwards.
204 pub fn insert(
205 &self,
206 id: &str,
207 name: Option<String>,
208 allowed: Grant,
209 connected: bool,
210 inner: T,
211 ) {
212 let mut devices = self.devices.lock().unwrap();
213 let previous = devices.get(id);
214 let generation = previous.map(|d| d.generation).unwrap_or(0);
215 // The lock is kept too: a fresh one would let an operation already in
216 // flight run beside the next, which is the thing it exists to prevent.
217 let gatt = previous
218 .map(|d| d.gatt.clone())
219 .unwrap_or_else(|| Arc::new(futures_util::lock::Mutex::new(())));
220 let allowed = match previous {
221 Some(d) => d.allowed.union(&allowed),
222 None => allowed,
223 };
224
225 devices.insert(
226 id.to_owned(),
227 Device {
228 name,
229 allowed,
230 connected,
231 generation,
232 gatt,
233 inner,
234 },
235 );
236 }
237
238 /// Read something out of a device's record.
239 pub fn get<R>(&self, id: &str, f: impl FnOnce(&Device<T>) -> R) -> Result<R> {
240 let devices = self.devices.lock().unwrap();
241 let device = devices
242 .get(id)
243 .ok_or_else(|| Error::InvalidState(format!("device {id} is no longer known")))?;
244 Ok(f(device))
245 }
246
247 /// Modify a device's record. Silently does nothing if it is gone.
248 pub fn update(&self, id: &str, f: impl FnOnce(&mut Device<T>)) {
249 if let Some(device) = self.devices.lock().unwrap().get_mut(id) {
250 f(device);
251 }
252 }
253
254 /// Find a device by something only the backend can recognise — a peripheral
255 /// pointer, an object path — and modify it.
256 ///
257 /// Only the Apple backend needs this: its events carry a `CBPeripheral`
258 /// rather than an id, so the device has to be found by identity.
259 #[cfg_attr(not(target_vendor = "apple"), allow(dead_code))]
260 pub fn update_where(
261 &self,
262 matches: impl Fn(&Device<T>) -> bool,
263 f: impl FnOnce(&mut Device<T>),
264 ) -> Option<String> {
265 let mut devices = self.devices.lock().unwrap();
266 let found = devices.iter_mut().find(|(_, d)| matches(d));
267 let (id, device) = found?;
268 let id = id.clone();
269 f(device);
270 Some(id)
271 }
272
273 /// The id of a device matching a backend-specific predicate.
274 ///
275 /// Unused where a backend's events already carry the device id rather than
276 /// a platform handle — `linux-hci`, Windows and the web all do.
277 #[cfg_attr(
278 any(
279 all(target_os = "linux", feature = "linux-hci"),
280 target_os = "windows",
281 target_arch = "wasm32",
282 ),
283 allow(dead_code)
284 )]
285 pub fn find(&self, matches: impl Fn(&Device<T>) -> bool) -> Option<String> {
286 self.devices
287 .lock()
288 .unwrap()
289 .iter()
290 .find(|(_, d)| matches(d))
291 .map(|(id, _)| id.clone())
292 }
293
294 /// The device's name, if it has one.
295 pub fn name(&self, id: &str) -> Option<String> {
296 self.get(id, |d| d.name.clone()).ok().flatten()
297 }
298
299 /// Whether the device is recorded as connected.
300 pub fn is_connected(&self, id: &str) -> bool {
301 self.get(id, |d| d.connected).unwrap_or(false)
302 }
303
304 /// The device's current generation, which a handle records when minted.
305 pub fn generation(&self, id: &str) -> Result<u64> {
306 self.get(id, |d| d.generation)
307 }
308
309 /// Every granted device's id.
310 pub fn ids(&self) -> Vec<String> {
311 self.devices.lock().unwrap().keys().cloned().collect()
312 }
313
314 /// Revoke a grant, returning the record so the backend can tear down its
315 /// side of it.
316 pub fn remove(&self, id: &str) -> Option<Device<T>> {
317 self.listeners.lock().unwrap().remove(id);
318 self.devices.lock().unwrap().remove(id)
319 }
320
321 /// The per-device allowlist from `request_device`.
322 pub fn check_allowed(&self, id: &str, uuid: &BluetoothUuid) -> Result<()> {
323 if self.get(id, |d| d.allowed.services.contains(uuid))? {
324 Ok(())
325 } else {
326 Err(Error::Security(format!(
327 "service {uuid} was not requested — list it in filters or optional_services"
328 )))
329 }
330 }
331
332 /// What this device was granted access to.
333 pub fn allowed_services(&self, id: &str) -> Result<BTreeSet<BluetoothUuid>> {
334 self.get(id, |d| d.allowed.services.clone())
335 }
336
337 /// The company identifiers this device's grant covers.
338 ///
339 /// Empty means none were asked for, which is the common case and means no
340 /// manufacturer data is reported at all.
341 /// Everything `id` was granted, or an empty grant if it is not known.
342 ///
343 /// An unknown device getting an empty grant rather than a full one is the
344 /// safe direction: it reports nothing rather than everything.
345 pub fn grant(&self, id: &str) -> Grant {
346 self.get(id, |d| d.allowed.clone()).unwrap_or_default()
347 }
348
349 /// Fail if handles minted at `generation` are stale, or the link is down.
350 /// Whether a handle taken at `generation` may still be used on `id`.
351 ///
352 /// The two failures are distinct, and the specification orders them: it
353 /// checks `gatt.connected` before it checks whether the object still
354 /// represents anything. The distinction is worth keeping because it tells
355 /// the caller what to do about it — a disconnection is something to
356 /// reconnect from and retry, whereas a stale handle survives reconnecting
357 /// and has to be rediscovered. Collapsing them into one error loses that.
358 pub fn check_generation(&self, id: &str, generation: u64) -> Result<()> {
359 // An id nobody has heard of is a stale object, not a lost connection,
360 // so this comes first.
361 let current = self.generation(id)?;
362 if !self.is_connected(id) {
363 return Err(Error::Network("the device is not connected".into()));
364 }
365 if current != generation {
366 return Err(Error::InvalidState(
367 "this GATT object is stale — the device disconnected or changed its services"
368 .into(),
369 ));
370 }
371 Ok(())
372 }
373
374 /// Take this device's GATT lock, held across one operation.
375 ///
376 /// Unused on the web: `navigator.bluetooth` serialises GATT operations
377 /// itself, so taking a second lock here would only add contention.
378 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
379 pub async fn gatt_lock(&self, id: &str) -> Result<futures_util::lock::OwnedMutexGuard<()>> {
380 Ok(self.get(id, |d| d.gatt.clone())?.lock_owned().await)
381 }
382
383 /// Watch for this device's service set changing — the specification's
384 /// `serviceadded`, `servicechanged` and `serviceremoved` between them.
385 ///
386 /// One signal rather than three, because that is what the platforms give:
387 /// each reports that the set changed and that existing handles are stale,
388 /// not which service it was. Inventing the distinction would mean
389 /// reporting detail nobody actually has.
390 pub fn watch_services_changed(&self, id: &str) -> mpsc::UnboundedReceiver<()> {
391 let (tx, rx) = mpsc::unbounded();
392 self.service_listeners
393 .lock()
394 .unwrap()
395 .entry(id.to_owned())
396 .or_default()
397 .push(tx);
398 rx
399 }
400
401 /// The service set changed: invalidate every handle into the device and
402 /// tell anyone watching.
403 ///
404 /// Only the platforms that detect it call this — CoreBluetooth's
405 /// `didModifyServices:` and Android's `onServiceChanged`. BlueZ, WinRT and
406 /// a raw ATT socket give no such signal, so on those targets this is
407 /// compiled and never reached; `watch_services_changed` there returns a
408 /// stream that stays silent rather than one that does not exist.
409 /// Every handle into this device is now stale, but the link is still up.
410 ///
411 /// Called by every backend, each from whatever its platform calls this:
412 /// CoreBluetooth's `didModifyServices:`, Android's `onServiceChanged`,
413 /// BlueZ's GATT objects appearing and vanishing, WinRT's
414 /// `GattServicesChanged`, the browser's `serviceschanged`, and — for
415 /// `linux-hci`, which has no stack to inherit it from — an indication on
416 /// the peer's own Service Changed characteristic.
417 pub fn mark_services_changed(&self, id: &str) {
418 self.update(id, |d| d.generation += 1);
419 let mut listeners = self.service_listeners.lock().unwrap();
420 if let Some(subscribers) = listeners.get_mut(id) {
421 subscribers.retain(|tx| tx.unbounded_send(()).is_ok());
422 }
423 }
424
425 /// A stream that yields once each time the device disconnects.
426 pub fn watch_disconnect(&self, id: &str) -> mpsc::UnboundedReceiver<()> {
427 let (tx, rx) = mpsc::unbounded();
428 self.listeners
429 .lock()
430 .unwrap()
431 .entry(id.to_owned())
432 .or_default()
433 .push(tx);
434 rx
435 }
436
437 /// Mark a device disconnected: drop the link, invalidate every handle into
438 /// it, and tell anyone watching.
439 pub fn mark_disconnected(&self, id: &str) {
440 self.update(id, |d| {
441 d.connected = false;
442 d.generation += 1;
443 });
444 let mut listeners = self.listeners.lock().unwrap();
445 if let Some(subscribers) = listeners.get_mut(id) {
446 subscribers.retain(|tx| tx.unbounded_send(()).is_ok());
447 if subscribers.is_empty() {
448 listeners.remove(id);
449 }
450 }
451 }
452}
453
454/// The methods every backend forwards to its registry, unchanged.
455///
456/// Ten one-line functions, written out six times, byte for byte — the backends
457/// differ in how they reach a radio and not at all in how they answer "is this
458/// device connected". Expanded inside each `impl Inner` rather than put behind
459/// a trait: exactly one backend is compiled into any build, so a trait would
460/// buy dynamic dispatch nobody needs, which is the same reasoning that keeps
461/// `Inner` a concrete type.
462///
463/// Every type is named absolutely, so this does not depend on which of them a
464/// given backend happens to have imported.
465#[macro_export]
466macro_rules! forward_to_registry {
467 () => {
468 pub fn device_name(&self, id: &str) -> Option<String> {
469 self.devices.name(id)
470 }
471
472 pub fn is_connected(&self, id: &str) -> bool {
473 self.devices.is_connected(id)
474 }
475
476 pub fn generation(&self, id: &str) -> $crate::error::Result<u64> {
477 self.devices.generation(id)
478 }
479
480 pub fn granted_devices(&self) -> Vec<String> {
481 self.devices.ids()
482 }
483
484 pub fn check_allowed(
485 &self,
486 id: &str,
487 uuid: &$crate::uuid::BluetoothUuid,
488 ) -> $crate::error::Result<()> {
489 self.devices.check_allowed(id, uuid)
490 }
491
492 pub fn allowed_services(
493 &self,
494 id: &str,
495 ) -> $crate::error::Result<std::collections::BTreeSet<$crate::uuid::BluetoothUuid>> {
496 self.devices.allowed_services(id)
497 }
498
499 pub fn check_generation(&self, id: &str, generation: u64) -> $crate::error::Result<()> {
500 self.devices.check_generation(id, generation)
501 }
502
503 pub fn watch_disconnect(
504 &self,
505 id: &str,
506 ) -> $crate::futures_channel::mpsc::UnboundedReceiver<()> {
507 self.devices.watch_disconnect(id)
508 }
509
510 pub fn watch_services_changed(
511 &self,
512 id: &str,
513 ) -> $crate::futures_channel::mpsc::UnboundedReceiver<()> {
514 self.devices.watch_services_changed(id)
515 }
516
517 pub fn grant(&self, id: &str) -> $crate::registry::Grant {
518 self.devices.grant(id)
519 }
520 };
521}
522
523pub use crate::forward_to_registry;
524
525#[cfg(test)]
526mod tests {
527 use super::*;
528 use crate::uuid::services;
529 use futures_executor::block_on;
530
531 fn registry() -> DeviceRegistry<u32> {
532 let registry = DeviceRegistry::default();
533 registry.insert(
534 "AA:BB",
535 Some("Sensor".into()),
536 BTreeSet::from([services::HEART_RATE]).into(),
537 true,
538 7u32,
539 );
540 registry
541 }
542
543 #[test]
544 fn an_unrequested_service_is_a_security_error() {
545 let registry = registry();
546 assert!(registry
547 .check_allowed("AA:BB", &services::HEART_RATE)
548 .is_ok());
549 let refused = registry.check_allowed("AA:BB", &services::BATTERY_SERVICE);
550 assert!(
551 matches!(refused, Err(Error::Security(_))),
552 "got {refused:?}"
553 );
554 }
555
556 #[test]
557 fn handles_go_stale_when_the_generation_moves() {
558 let registry = registry();
559 assert!(registry.check_generation("AA:BB", 0).is_ok());
560
561 registry.mark_disconnected("AA:BB");
562
563 // Both reasons now apply, and the specification orders them: being
564 // disconnected is reported ahead of the handle being stale, because
565 // reconnecting is what the caller has to do first either way.
566 assert!(matches!(
567 registry.check_generation("AA:BB", 0),
568 Err(Error::Network(_))
569 ));
570 assert!(matches!(
571 registry.check_generation("AA:BB", 1),
572 Err(Error::Network(_))
573 ));
574 assert!(!registry.is_connected("AA:BB"));
575 }
576
577 /// Reconnecting clears the disconnection but not the staleness: handles
578 /// taken before it have to be rediscovered, and say so.
579 #[test]
580 fn a_handle_from_before_a_reconnect_is_stale_not_disconnected() {
581 let registry = registry();
582 let before = registry.generation("AA:BB").unwrap();
583
584 registry.mark_disconnected("AA:BB");
585 registry.update("AA:BB", |d| d.connected = true);
586
587 assert!(matches!(
588 registry.check_generation("AA:BB", before),
589 Err(Error::InvalidState(_))
590 ));
591 let now = registry.generation("AA:BB").unwrap();
592 assert!(registry.check_generation("AA:BB", now).is_ok());
593 }
594
595 #[test]
596 fn disconnecting_notifies_watchers() {
597 let registry = registry();
598 let mut watcher = registry.watch_disconnect("AA:BB");
599 registry.mark_disconnected("AA:BB");
600 assert!(block_on(futures_util::StreamExt::next(&mut watcher)).is_some());
601 }
602
603 #[test]
604 fn an_unknown_device_is_an_invalid_state_not_a_panic() {
605 let registry: DeviceRegistry<u32> = DeviceRegistry::default();
606 assert!(matches!(
607 registry.generation("nope"),
608 Err(Error::InvalidState(_))
609 ));
610 assert!(matches!(
611 registry.check_generation("nope", 0),
612 Err(Error::InvalidState(_))
613 ));
614 assert!(registry.name("nope").is_none());
615 assert!(!registry.is_connected("nope"));
616 }
617
618 #[test]
619 fn the_gatt_lock_serialises_operations() {
620 let registry = registry();
621 block_on(async {
622 let first = registry.gatt_lock("AA:BB").await.unwrap();
623 // A second attempt must not be ready while the first is held.
624 let second = registry.gatt_lock("AA:BB");
625 let pending = futures_util::poll!(std::pin::pin!(second));
626 assert!(pending.is_pending(), "the lock let two operations through");
627 drop(first);
628 });
629 }
630
631 #[test]
632 fn devices_can_be_found_by_backend_specific_identity() {
633 let registry = registry();
634 // A backend looks its own payload up — a pointer, a path, an address.
635 assert_eq!(registry.find(|d| d.inner == 7), Some("AA:BB".into()));
636 assert_eq!(registry.find(|d| d.inner == 99), None);
637
638 registry.update_where(|d| d.inner == 7, |d| d.name = Some("Renamed".into()));
639 assert_eq!(registry.name("AA:BB").as_deref(), Some("Renamed"));
640 }
641
642 /// A second `requestDevice` for the same device must not take away what
643 /// the first one granted.
644 ///
645 /// The specification unions: *"add the contents of
646 /// `allowedDevice.allowedServices` to `grantedServiceUUIDs`"*. Replacing
647 /// instead would revoke a service silently — a caller still holding it
648 /// starts getting `SecurityError` for something it was given.
649 #[test]
650 fn a_narrower_second_grant_does_not_revoke_the_first() {
651 let registry = DeviceRegistry::<()>::default();
652 let battery = BluetoothUuid::from_u16(0x180F);
653 let info = BluetoothUuid::from_u16(0x180A);
654
655 registry.insert(
656 "dev",
657 None,
658 Grant {
659 services: [battery, info].into_iter().collect(),
660 manufacturer_data: vec![0x004C],
661 },
662 false,
663 (),
664 );
665 // The same device again, asking for less.
666 registry.insert(
667 "dev",
668 None,
669 Grant {
670 services: [battery].into_iter().collect(),
671 manufacturer_data: vec![],
672 },
673 false,
674 (),
675 );
676
677 assert!(
678 registry.check_allowed("dev", &info).is_ok(),
679 "the first grant's service is still allowed"
680 );
681 assert!(registry.check_allowed("dev", &battery).is_ok());
682 assert_eq!(
683 registry.grant("dev").manufacturer_data,
684 vec![0x004C],
685 "and so is the company it was granted"
686 );
687 }
688
689 /// A re-grant must not revive handles that went stale.
690 ///
691 /// `generation` counts how many times every handle into a device became
692 /// invalid. A handle carries the value it was made at, and
693 /// `check_generation` compares them. If a re-grant reset the counter, a
694 /// handle captured before a disconnect would match again afterwards and be
695 /// treated as live — pointing at attributes the peer is free to have
696 /// rearranged while it was away.
697 #[test]
698 fn a_re_grant_does_not_revive_stale_handles() {
699 let registry = DeviceRegistry::<()>::default();
700 let grant = || Grant {
701 services: [BluetoothUuid::from_u16(0x180F)].into_iter().collect(),
702 manufacturer_data: vec![],
703 };
704
705 registry.insert("dev", None, grant(), true, ());
706 let captured = registry.generation("dev").unwrap();
707 assert!(registry.check_generation("dev", captured).is_ok());
708
709 // The link drops: everything handed out before is now stale.
710 registry.mark_disconnected("dev");
711
712 // The device is granted again and reconnects.
713 registry.insert("dev", None, grant(), true, ());
714 assert_eq!(
715 registry
716 .check_generation("dev", captured)
717 .unwrap_err()
718 .to_string(),
719 Error::InvalidState(
720 "this GATT object is stale — the device disconnected or changed its services"
721 .into()
722 )
723 .to_string(),
724 "the handle from before the disconnect must stay stale"
725 );
726 // And a handle made now is fine.
727 let fresh = registry.generation("dev").unwrap();
728 assert!(registry.check_generation("dev", fresh).is_ok());
729 }
730
731 #[test]
732 fn forgetting_removes_the_grant_and_its_watchers() {
733 let registry = registry();
734 let _watcher = registry.watch_disconnect("AA:BB");
735 assert!(registry.remove("AA:BB").is_some());
736 assert!(registry.ids().is_empty());
737 assert!(registry.remove("AA:BB").is_none());
738 }
739}