Skip to main content
QAROS Rust API Dev (main) · versions: Dev (main) · Developer Guide

qaros/
member_hub.rs

1//! Member hubs: join the QAROS hub of one PC to the session of the hub on another PC, when an
2//! application already connects the two PCs.
3//!
4//! 1. On the primary's PC, [`Runtime::create_member_hub_invitation`] returns an invitation the
5//!    primary hub signed. [`MemberHubInvitation::serialize`] it and send the bytes to the
6//!    application on the joining PC over its own trusted channel.
7//! 2. On the joining PC, [`crate::Library::deserialize_member_hub_invitation`] reads it and
8//!    [`Runtime::join_hub_as_member`] hands it to the hub there, which joins the primary and
9//!    restarts into its session. Then onboard the application itself as a local app
10//!    ([`crate::OnboardMethod::LocalApp`]).
11//!
12//! An invitation is a secret bearer credential until it expires or is used up: never log it.
13//! Windows only; elsewhere the calls fail with [`crate::StatusCode::NOT_IMPLEMENTED`].
14
15use std::num::NonZeroU32;
16use std::ops::{BitOr, BitOrAssign};
17use std::time::Duration;
18
19use std::ffi::CString;
20use std::ptr::{self, NonNull};
21use std::rc::Rc;
22
23use qaros_sys::{self as sys, defaults};
24
25use crate::callbacks::BlockingOptions;
26use crate::cancel::CancelToken;
27use crate::error::{Error, Result, StatusCode, check};
28use crate::library::{Library, LibraryInner, require_handle};
29use crate::runtime::{Runtime, optional_milliseconds};
30use crate::strings;
31
32/// The permissions a member-hub invitation grants at the primary hub
33/// (`QarMemberHubInvitationPermissionFlagBits`). Combine them with `|`.
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
35pub struct MemberHubPermissions(u32);
36
37impl MemberHubPermissions {
38    /// A hub the primary does not know joins as a new member.
39    pub const JOIN: Self = Self(0x1);
40    /// A member the primary already admitted (and has not removed) is answered again; lets a
41    /// member that lost its membership rejoin.
42    pub const REJOIN: Self = Self(0x2);
43    /// A member the primary's operator removed is admitted again.
44    pub const READMIT: Self = Self(0x4);
45    /// A hub that was a primary of its own moves its paired devices, launcher children and
46    /// approved local apps into the primary's session.
47    pub const BRING_DEVICES: Self = Self(0x8);
48
49    /// The bits, as `QarMemberHubInvitationPermissionFlags`.
50    pub const fn bits(self) -> u32 {
51        self.0
52    }
53
54    /// Whether every permission of `other` is set.
55    pub const fn contains(self, other: Self) -> bool {
56        self.0 & other.0 == other.0
57    }
58}
59
60impl BitOr for MemberHubPermissions {
61    type Output = Self;
62
63    fn bitor(self, other: Self) -> Self {
64        Self(self.0 | other.0)
65    }
66}
67
68impl BitOrAssign for MemberHubPermissions {
69    fn bitor_assign(&mut self, other: Self) {
70        self.0 |= other.0;
71    }
72}
73
74/// Options for [`Runtime::create_member_hub_invitation`] (`QarMemberHubInvitationInit`). `None`
75/// selects the C API's default.
76#[derive(Clone, Debug, Default)]
77pub struct MemberHubInvitationConfig {
78    /// How long the invitation can be used, in whole seconds (rounded down). `None`: 24 h. At
79    /// most 7 days, else [`crate::StatusCode::ARGUMENT_NOT_SUPPORTED`]. Under one second, or over
80    /// `u32::MAX` seconds, is [`crate::Error::InvalidArgument`] before the call.
81    pub lifetime: Option<Duration>,
82    /// How many hubs may join with it. `None`: 1. At most 64, and never more than the calling
83    /// app's remaining quota of member hubs.
84    pub max_uses: Option<NonZeroU32>,
85    /// `None`: [`MemberHubPermissions::JOIN`] | [`MemberHubPermissions::REJOIN`] |
86    /// [`MemberHubPermissions::BRING_DEVICES`]. An empty set is [`crate::Error::InvalidArgument`]
87    /// before the call, since the C API reads zero as the default.
88    pub permissions: Option<MemberHubPermissions>,
89    /// A UTF-8 label of at most 64 bytes, shown in the primary hub's visualizer next to the
90    /// invitation.
91    pub label: Option<String>,
92    /// Also grant one remote app on the joining PC (`QarMemberHubInvitationAppGrantExt`), under
93    /// this app tag, with the app tag rules of [`crate::OnboardMethod::LocalApp`]. The grant is
94    /// bound to the calling app's approval and the tag. Only a member hub of this primary redeems
95    /// it (a hub that is not a member ignores it and prompts its operator). There, the first
96    /// executable that onboards as a local app with the invitation
97    /// ([`crate::OnboardExtensions::remote_app_grant`]) is approved there without a prompt;
98    /// later starts of that executable onboard with no invitation and no prompt, under the same
99    /// peer id while no other live process holds it. A different executable is refused the grant
100    /// once it is redeemed. One grant admits one app on one member PC, however many hubs
101    /// `max_uses` lets join: issue one tag per remote app. With a grant, the calling app's own
102    /// approval is not extended to the member hub (without one it is). Revoking the calling app's
103    /// approval, or the granted one, on the primary revokes the granted app.
104    pub app_grant_tag: Option<String>,
105}
106
107/// Options for [`Runtime::join_hub_as_member`] (`QarJoinHubAsMemberInit`). `None` selects the
108/// C API's default; under 1 ms, or over `u32::MAX` milliseconds, is
109/// [`crate::Error::InvalidArgument`] before the call, since the C API reads zero as the default.
110#[derive(Clone, Copy, Debug, Default)]
111pub struct JoinHubAsMemberConfig {
112    /// How long to wait for a hub this call started to accept connections. `None`: 60 s.
113    pub hub_start_timeout: Option<Duration>,
114    /// How long to wait for the hub to come back as a member after its restart. `None`: 120 s.
115    pub restart_timeout: Option<Duration>,
116}
117
118/// A member-hub invitation (`QarMemberHubInvitation`), destroyed on drop
119/// (`qar_member_hub_invitation_handle_destroy`). A secret bearer credential: send its bytes only
120/// over a trusted channel and never log them. The primary hub's operator sees it in the
121/// visualizer and can revoke it.
122#[derive(Debug)]
123pub struct MemberHubInvitation {
124    handle: NonNull<sys::QarMemberHubInvitation>,
125    library: Rc<LibraryInner>,
126}
127
128impl MemberHubInvitation {
129    fn from_handle(
130        library: &Rc<LibraryInner>,
131        handle: *mut sys::QarMemberHubInvitation,
132        function: &'static str,
133    ) -> Result<Self> {
134        Ok(Self {
135            handle: require_handle(handle, function)?,
136            library: Rc::clone(library),
137        })
138    }
139
140    /// The invitation's bytes for the application's own channel
141    /// (`qar_member_hub_invitation_serialized_size`, `qar_member_hub_invitation_serialize`):
142    /// UTF-8 JSON of at most 16 KiB that carries the invitation's secret.
143    pub fn serialize(&self) -> Result<Vec<u8>> {
144        let api = &self.library.api;
145        let mut size = 0_usize;
146        // SAFETY: live invitation; valid out-pointer.
147        let result = unsafe {
148            (api.qar_impl_member_hub_invitation_serialized_size)(
149                self.handle.as_ptr(),
150                &raw mut size,
151            )
152        };
153        check(api, "qar_member_hub_invitation_serialized_size", result)?;
154        let mut bytes = vec![0_u8; size];
155        let mut written = 0_usize;
156        // SAFETY: live invitation; the buffer is writable for its length; valid out-pointer.
157        let result = unsafe {
158            (api.qar_impl_member_hub_invitation_serialize)(
159                self.handle.as_ptr(),
160                bytes.as_mut_ptr(),
161                bytes.len(),
162                &raw mut written,
163            )
164        };
165        check(api, "qar_member_hub_invitation_serialize", result)?;
166        if written > bytes.len() {
167            return Err(Error::Api {
168                function: "qar_member_hub_invitation_serialize",
169                code: StatusCode::ARGUMENT_NOT_SUPPORTED,
170                message: format!("needs {written} bytes after reporting {size}"),
171                causes: Vec::new(),
172            });
173        }
174        bytes.truncate(written);
175        Ok(bytes)
176    }
177
178    /// The `QarMemberHubInvitation` handle, for raw calls through [`Library::raw_api`]. Taking
179    /// the pointer is safe; using it is `unsafe`, under the rules of [`crate::Session::as_raw`]
180    /// for an invitation: valid while this value lives, never destroyed by the caller.
181    pub fn as_raw(&self) -> *mut sys::QarMemberHubInvitation {
182        self.handle.as_ptr()
183    }
184
185    pub(crate) fn as_ptr(&self) -> *const sys::QarMemberHubInvitation {
186        self.handle.as_ptr()
187    }
188}
189
190impl Drop for MemberHubInvitation {
191    fn drop(&mut self) {
192        // SAFETY: owned handle, destroyed once; the calls that take it borrow it only for the
193        // call.
194        unsafe {
195            (self
196                .library
197                .api
198                .qar_impl_member_hub_invitation_handle_destroy)(self.handle.as_ptr());
199        };
200    }
201}
202
203impl Library {
204    /// Reads an invitation from the bytes [`MemberHubInvitation::serialize`] wrote
205    /// (`qar_member_hub_invitation_deserialize`). Strict: an invitation with an unknown or missing
206    /// field, of another kind or version, out of its bounds, or over 16 KiB fails with
207    /// [`StatusCode::MEMBER_INVITATION_INVALID`]. Its signature is checked by
208    /// [`Runtime::join_hub_as_member`], not here.
209    pub fn deserialize_member_hub_invitation(
210        &self,
211        wire_bytes: &[u8],
212    ) -> Result<MemberHubInvitation> {
213        let api = &self.inner.api;
214        let mut handle: *mut sys::QarMemberHubInvitation = ptr::null_mut();
215        // SAFETY: wire_bytes is readable for its length; valid out-pointer.
216        let result = unsafe {
217            (api.qar_impl_member_hub_invitation_deserialize)(
218                wire_bytes.as_ptr(),
219                wire_bytes.len(),
220                &raw mut handle,
221            )
222        };
223        check(api, "qar_member_hub_invitation_deserialize", result)?;
224        MemberHubInvitation::from_handle(
225            &self.inner,
226            handle,
227            "qar_member_hub_invitation_deserialize",
228        )
229    }
230}
231
232impl Runtime {
233    /// Asks the QAROS hub on this PC, the session's primary hub, for a member-hub invitation
234    /// (`qar_runtime_create_member_hub_invitation`). Needs no session: the hub identifies this
235    /// process as for a local app, and answers only an application it approved with the right to
236    /// bring in member hubs and with quota left (spent per hub the invitation admits, not per
237    /// invitation). It never prompts. The C call takes a cancel token but no progress callback.
238    ///
239    /// Fails with [`StatusCode::ARGUMENT_NOT_SUPPORTED`] for a field out of range,
240    /// [`StatusCode::ONBOARDING_HUB_UNREACHABLE`], [`StatusCode::ONBOARDING_HUB_NOT_AUTHENTIC`],
241    /// [`StatusCode::ONBOARDING_APPROVAL_DENIED`] (the app is not approved),
242    /// [`StatusCode::MEMBER_SPONSOR_NOT_ALLOWED`], [`StatusCode::MEMBER_SPONSOR_QUOTA_EXCEEDED`],
243    /// [`StatusCode::SESSION_WIDE_ACTION_ON_MEMBER`] (create it on the primary's PC) or
244    /// [`StatusCode::NOT_IMPLEMENTED`] (not on Windows).
245    pub fn create_member_hub_invitation(
246        &self,
247        config: &MemberHubInvitationConfig,
248        cancel: Option<&CancelToken>,
249    ) -> Result<MemberHubInvitation> {
250        let mut init = defaults::qar_member_hub_invitation_init_default();
251        init.lifetime_seconds = lifetime_seconds(config.lifetime)?;
252        init.max_uses = config.max_uses.map_or(0, NonZeroU32::get);
253        init.permissions = match config.permissions {
254            None => 0,
255            Some(permissions) if permissions.bits() == 0 => {
256                return Err(Error::InvalidArgument(
257                    "an empty permission set; pass None for the default".to_string(),
258                ));
259            }
260            Some(permissions) => permissions.bits(),
261        };
262        let label = strings::optional_c_string(config.label.as_deref(), "invitation label")?;
263        init.label = strings::pointer_or_null(label.as_ref());
264        let app_grant_tag: Option<CString> =
265            strings::optional_c_string(config.app_grant_tag.as_deref(), "app grant tag")?;
266        let mut app_grant = defaults::qar_member_hub_invitation_app_grant_ext_default();
267        if let Some(tag) = &app_grant_tag {
268            app_grant.app_tag = tag.as_ptr();
269            init.header.next = (&raw mut app_grant).cast();
270        }
271
272        let api = &self.inner.library.api;
273        let cancel_pointer = cancel.map_or(ptr::null_mut(), CancelToken::as_ptr);
274        let mut handle: *mut sys::QarMemberHubInvitation = ptr::null_mut();
275        // SAFETY: live runtime; init, its extension and strings live for the call; the token is
276        // borrowed for the call; valid out-pointer.
277        let result = unsafe {
278            (api.qar_impl_runtime_create_member_hub_invitation)(
279                self.as_raw(),
280                &raw const init,
281                cancel_pointer,
282                &raw mut handle,
283            )
284        };
285        check(api, "qar_runtime_create_member_hub_invitation", result)?;
286        MemberHubInvitation::from_handle(
287            &self.inner.library,
288            handle,
289            "qar_runtime_create_member_hub_invitation",
290        )
291    }
292
293    /// Joins the QAROS hub on this PC to the invitation's primary hub as a member
294    /// (`qar_runtime_join_hub_as_member`). This joins the PC's hub, not the calling application:
295    /// it does not onboard. Once it returns, onboard as a local app, which then succeeds without a
296    /// prompt for the application that created the invitation.
297    ///
298    /// Starts the installed hub when none runs for this user; checks the invitation's signature,
299    /// expiry and whether this PC trusts its primary; joins, rejoins or readmits the hub and blocks
300    /// through the hub's restart into the primary's session. Called again with an invitation of
301    /// the primary the hub is already a member of, it succeeds at once. The invitation is borrowed
302    /// for the call.
303    ///
304    /// Fails with [`StatusCode::MEMBER_INVITATION_INVALID`],
305    /// [`StatusCode::MEMBER_INVITATION_EXPIRED`], [`StatusCode::MEMBER_INVITATION_USED_UP`],
306    /// [`StatusCode::MEMBER_INVITATION_REVOKED`] (ask for a new invitation),
307    /// [`StatusCode::MEMBER_INVITATION_PRIMARY_NOT_ALLOWED`],
308    /// [`StatusCode::MEMBER_INVITATION_POLICY_NOT_PROTECTED`], [`StatusCode::MEMBER_JOIN_REFUSED`],
309    /// [`StatusCode::MEMBER_REMOVED`], [`StatusCode::PRIMARY_UNREACHABLE`],
310    /// [`StatusCode::HUB_LIFECYCLE_OPERATION_RUNNING`] (retry),
311    /// [`StatusCode::ONBOARDING_HUB_UNREACHABLE`], [`StatusCode::ONBOARDING_HUB_NOT_AUTHENTIC`],
312    /// [`StatusCode::TIMEOUT`] (the join is committed: calling again succeeds once the hub is
313    /// back) or [`StatusCode::NOT_IMPLEMENTED`] (not on Windows).
314    pub fn join_hub_as_member(
315        &self,
316        invitation: &MemberHubInvitation,
317        config: &JoinHubAsMemberConfig,
318        options: &BlockingOptions<'_>,
319    ) -> Result<()> {
320        let mut init = defaults::qar_join_hub_as_member_init_default();
321        init.invitation = invitation.as_ptr();
322        init.hub_start_timeout_ms =
323            optional_milliseconds(config.hub_start_timeout, "hub start timeout")?;
324        init.restart_timeout_ms = optional_milliseconds(config.restart_timeout, "restart timeout")?;
325        let api = &self.inner.library.api;
326        // SAFETY: live runtime; init and the invitation it borrows live for the call; the
327        // progress state and cancel token are borrowed from options for the call.
328        let result = unsafe {
329            (api.qar_impl_runtime_join_hub_as_member)(
330                self.as_raw(),
331                &raw const init,
332                options.progress_callback(),
333                options.progress_state(),
334                options.cancel_pointer(),
335            )
336        };
337        check(api, "qar_runtime_join_hub_as_member", result)
338    }
339}
340
341fn lifetime_seconds(lifetime: Option<Duration>) -> Result<u32> {
342    let Some(lifetime) = lifetime else {
343        return Ok(0);
344    };
345    match u32::try_from(lifetime.as_secs()) {
346        Ok(0) => Err(Error::InvalidArgument(
347            "an invitation lifetime under one second; pass None for the default".to_string(),
348        )),
349        Ok(seconds) => Ok(seconds),
350        Err(_) => Err(Error::InvalidArgument(format!(
351            "invitation lifetime {lifetime:?} exceeds u32 seconds"
352        ))),
353    }
354}