Skip to main content

moq_ext_sources/
portal_grant.rs

1//! The desktop portal's screen-sharing grant, kept in a file across runs.
2
3use std::{
4    io::Write,
5    path::{Path, PathBuf},
6};
7
8use moq_video::capture::portal::{Kind, RestoreToken, Selection};
9use tracing::{debug, warn};
10
11/// A desktop portal grant kept in a file, so a later run can skip the picker.
12///
13/// [`PortalGrant::selection`] seeds a [`Selection`] with the stored restore
14/// token and stores each new token the portal grants. On a compositor that
15/// keeps grants, the next run then shares the same screen or window without
16/// asking.
17///
18/// The file survives an open that is killed or refused, since the open takes
19/// the token before asking the portal. Once the portal has granted a new
20/// token, the end of the stream (for example the user stopped sharing)
21/// deletes the file, so the next run asks again, unless
22/// [`keep_after_end`](Self::keep_after_end) is set.
23///
24/// The file holds the token as text, readable only by its owner.
25/// [`VideoOpenOptions::with_portal_grants`](crate::spec::VideoOpenOptions::with_portal_grants)
26/// keeps grants for sources opened from a specifier.
27///
28/// # Examples
29///
30/// ```no_run
31/// # async fn example() -> Result<(), moq_ext_sources::Error> {
32/// use moq_ext_sources::{PortalGrant, VideoSource};
33/// use moq_video::capture::{self, portal::Kind};
34///
35/// let grant = PortalGrant::in_config_dir(Kind::Screen, "my-app").expect("a home directory");
36/// let mut config = capture::Config::default();
37/// config.source = capture::Source::Portal(grant.selection());
38/// let screen = VideoSource::capture(config).await?;
39/// # let _ = screen;
40/// # Ok(())
41/// # }
42/// ```
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct PortalGrant {
45    kind: Kind,
46    path: PathBuf,
47    keep_after_end: bool,
48}
49
50impl PortalGrant {
51    /// Creates a grant of `kind` stored in the file at `path`.
52    pub fn new(kind: Kind, path: impl Into<PathBuf>) -> Self {
53        Self {
54            kind,
55            path: path.into(),
56            keep_after_end: false,
57        }
58    }
59
60    /// Keeps the stored grant when the stream ends, until a new one replaces it.
61    ///
62    /// The next run then tries the stored token, and the portal asks only if
63    /// the compositor no longer honors it.
64    #[must_use]
65    pub fn keep_after_end(mut self) -> Self {
66        self.keep_after_end = true;
67        self
68    }
69
70    /// Creates a grant of `kind` stored in the user's config directory.
71    ///
72    /// The file is `<app>/portal/{screen,window}.token` under
73    /// `$XDG_CONFIG_HOME`, or `~/.config` when that is unset or not absolute.
74    /// Returns `None` without either, or when `app` is not a single file name.
75    pub fn in_config_dir(kind: Kind, app: &str) -> Option<Self> {
76        if app.is_empty() || Path::new(app).file_name() != Some(app.as_ref()) {
77            warn!(app, "the portal grant's app name is not a file name");
78            return None;
79        }
80        let config = std::env::var_os("XDG_CONFIG_HOME")
81            .map(PathBuf::from)
82            .filter(|dir| dir.is_absolute())
83            .or_else(|| {
84                std::env::var_os("HOME")
85                    .map(PathBuf::from)
86                    .filter(|home| home.is_absolute())
87                    .map(|home| home.join(".config"))
88            })?;
89        let name = match kind {
90            Kind::Screen => "screen.token",
91            Kind::Window => "window.token",
92        };
93        Some(Self::new(kind, config.join(app).join("portal").join(name)))
94    }
95
96    /// Returns the kind of source the grant is for.
97    pub fn kind(&self) -> Kind {
98        self.kind
99    }
100
101    /// Returns the file that holds the grant.
102    pub fn path(&self) -> &Path {
103        &self.path
104    }
105
106    /// Returns a selection seeded with the stored token, which stores each new one.
107    ///
108    /// A missing or unreadable file gives a selection without a token, so the
109    /// portal asks. New tokens are stored by a task that ends with the last
110    /// clone of the selection; outside a tokio runtime they are not stored.
111    pub fn selection(&self) -> Selection {
112        let mut selection = Selection::new(self.kind);
113        if let Some(token) = self.load() {
114            debug!(path = %self.path.display(), "seeding the portal with a stored grant");
115            selection = selection.with_restore_token(token);
116        }
117        let Ok(runtime) = tokio::runtime::Handle::try_current() else {
118            warn!(
119                path = %self.path.display(),
120                "no tokio runtime, so new portal grants are not stored",
121            );
122            return selection;
123        };
124        let path = self.path.clone();
125        let keep_after_end = self.keep_after_end;
126        let mut tokens = selection.restore_token();
127        runtime.spawn(async move {
128            let mut granted = false;
129            while let Some(token) = tokens.changed().await {
130                apply(&path, update(&mut granted, keep_after_end, token.as_ref()));
131            }
132        });
133        selection
134    }
135
136    /// Reads the stored token, or `None` if there is none.
137    fn load(&self) -> Option<RestoreToken> {
138        match std::fs::read_to_string(&self.path) {
139            Ok(token) if !token.trim().is_empty() => Some(RestoreToken::new(token.trim())),
140            Ok(_) => None,
141            Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
142            Err(err) => {
143                warn!(path = %self.path.display(), %err, "cannot read the stored portal grant");
144                None
145            }
146        }
147    }
148}
149
150/// What to do with the stored file when the selection's token changes.
151#[derive(Debug, PartialEq, Eq)]
152enum Update<'a> {
153    /// Writes the new token.
154    Store(&'a RestoreToken),
155    /// Leaves the file as it is.
156    Keep,
157    /// Deletes the file.
158    Delete,
159}
160
161/// Decides what a change of the token to `token` does to the file.
162///
163/// `granted` is set by the first token. A `None` before it is an open taking
164/// the stored token; a `None` after it is the end of the stream.
165fn update<'a>(
166    granted: &mut bool,
167    keep_after_end: bool,
168    token: Option<&'a RestoreToken>,
169) -> Update<'a> {
170    match token {
171        Some(token) => {
172            *granted = true;
173            Update::Store(token)
174        }
175        None if *granted && !keep_after_end => Update::Delete,
176        None => Update::Keep,
177    }
178}
179
180/// Carries out `update` on the file at `path`.
181fn apply(path: &Path, update: Update<'_>) {
182    match update {
183        Update::Store(token) => match write_private(path, token.as_str()) {
184            Ok(()) => debug!(path = %path.display(), "portal grant stored"),
185            Err(err) => warn!(path = %path.display(), %err, "cannot store the portal grant"),
186        },
187        Update::Keep => {
188            debug!(path = %path.display(), "the portal grant has no new token, keeping the stored one");
189        }
190        Update::Delete => match std::fs::remove_file(path) {
191            Ok(()) => debug!(path = %path.display(), "portal grant ended, deleted"),
192            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
193            Err(err) => warn!(path = %path.display(), %err, "cannot delete the portal grant"),
194        },
195    }
196}
197
198/// Writes `contents` to `path` with mode 0600 through a renamed temporary file.
199fn write_private(path: &Path, contents: &str) -> std::io::Result<()> {
200    use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
201
202    if let Some(dir) = path.parent() {
203        std::fs::create_dir_all(dir)?;
204    }
205    let mut temp = path.as_os_str().to_owned();
206    temp.push(".tmp");
207    let temp = PathBuf::from(temp);
208    let mut file = std::fs::OpenOptions::new()
209        .write(true)
210        .create(true)
211        .truncate(true)
212        .mode(0o600)
213        .open(&temp)?;
214    file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
215    file.write_all(contents.as_bytes())?;
216    drop(file);
217    std::fs::rename(&temp, path)
218}
219
220#[cfg(test)]
221mod tests {
222    use std::os::unix::fs::PermissionsExt;
223
224    use super::*;
225
226    /// Returns a fresh directory for one test, removed by the caller.
227    fn test_dir(name: &str) -> PathBuf {
228        let dir = std::env::temp_dir().join(format!("portal-grant-{name}-{}", std::process::id()));
229        std::fs::remove_dir_all(&dir).ok();
230        dir
231    }
232
233    #[test]
234    fn write_private_replaces_the_file_with_a_private_one() {
235        let dir = test_dir("write");
236        let path = dir.join("portal").join("screen.token");
237        write_private(&path, "first").unwrap();
238        assert_eq!(std::fs::read_to_string(&path).unwrap(), "first");
239        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
240
241        write_private(&path, "second").unwrap();
242        assert_eq!(std::fs::read_to_string(&path).unwrap(), "second");
243        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
244        assert_eq!(mode & 0o777, 0o600);
245        std::fs::remove_dir_all(dir).ok();
246    }
247
248    #[test]
249    fn none_keeps_the_file_until_the_first_grant_and_deletes_it_after() {
250        let token = RestoreToken::new("grant");
251        let mut granted = false;
252        // The open takes the stored token, or the compositor refuses it.
253        assert_eq!(update(&mut granted, false, None), Update::Keep);
254        assert_eq!(update(&mut granted, false, None), Update::Keep);
255        // The portal grants a token, and later the user stops sharing.
256        assert_eq!(
257            update(&mut granted, false, Some(&token)),
258            Update::Store(&token)
259        );
260        assert_eq!(update(&mut granted, false, None), Update::Delete);
261        // A reopen takes and replaces the token again.
262        assert_eq!(
263            update(&mut granted, false, Some(&token)),
264            Update::Store(&token)
265        );
266    }
267
268    #[test]
269    fn keep_after_end_keeps_the_file_on_every_none() {
270        let token = RestoreToken::new("grant");
271        let mut granted = false;
272        assert_eq!(update(&mut granted, true, None), Update::Keep);
273        assert_eq!(
274            update(&mut granted, true, Some(&token)),
275            Update::Store(&token)
276        );
277        // The stream ends: the file stays until a new grant replaces it.
278        assert_eq!(update(&mut granted, true, None), Update::Keep);
279        assert_eq!(update(&mut granted, true, None), Update::Keep);
280        let next = RestoreToken::new("next");
281        assert_eq!(
282            update(&mut granted, true, Some(&next)),
283            Update::Store(&next)
284        );
285    }
286
287    #[test]
288    fn keep_after_end_is_off_by_default() {
289        let grant = PortalGrant::new(Kind::Screen, "/tmp/screen.token");
290        assert!(!grant.keep_after_end);
291        assert!(grant.keep_after_end().keep_after_end);
292    }
293
294    #[test]
295    fn apply_stores_keeps_and_deletes_the_file() {
296        let dir = test_dir("apply");
297        let path = dir.join("window.token");
298        let token = RestoreToken::new("grant");
299        apply(&path, Update::Store(&token));
300        assert_eq!(std::fs::read_to_string(&path).unwrap(), "grant");
301        apply(&path, Update::Keep);
302        assert_eq!(std::fs::read_to_string(&path).unwrap(), "grant");
303        apply(&path, Update::Delete);
304        assert!(!path.exists());
305        apply(&path, Update::Delete);
306        std::fs::remove_dir_all(dir).ok();
307    }
308
309    #[test]
310    fn selection_outside_a_runtime_is_seeded_without_a_task() {
311        let dir = test_dir("no-runtime");
312        let grant = PortalGrant::new(Kind::Screen, dir.join("screen.token"));
313        write_private(grant.path(), "grant").unwrap();
314        let token = grant.selection().restore_token().token();
315        assert_eq!(token, Some(RestoreToken::new("grant")));
316        std::fs::remove_dir_all(dir).ok();
317    }
318
319    #[tokio::test]
320    async fn selection_is_seeded_with_the_stored_token() {
321        let dir = test_dir("seed");
322        let grant = PortalGrant::new(Kind::Window, dir.join("window.token"));
323        assert_eq!(grant.selection().restore_token().token(), None);
324
325        write_private(grant.path(), "grant\n").unwrap();
326        let token = grant.selection().restore_token().token();
327        assert_eq!(token, Some(RestoreToken::new("grant")));
328        std::fs::remove_dir_all(dir).ok();
329    }
330
331    #[test]
332    fn in_config_dir_names_the_file_after_the_app_and_kind() {
333        let Some(grant) = PortalGrant::in_config_dir(Kind::Screen, "app") else {
334            return;
335        };
336        assert!(grant.path().ends_with("app/portal/screen.token"));
337        assert!(grant.path().is_absolute());
338        assert_eq!(grant.kind(), Kind::Screen);
339    }
340
341    #[test]
342    fn in_config_dir_takes_only_a_file_name() {
343        for app in ["", ".", "..", "../x", "a/b", "/tmp/x"] {
344            assert_eq!(
345                PortalGrant::in_config_dir(Kind::Window, app),
346                None,
347                "{app:?} is not a file name",
348            );
349        }
350    }
351}