1
// org.freedesktop.Secret.Session
2

            
3
use std::{
4
    fmt,
5
    sync::Arc,
6
    time::{Duration, Instant},
7
};
8

            
9
use oo7::{Key, dbus::ServiceError};
10
use tokio::sync::Mutex;
11
use zbus::{
12
    interface,
13
    names::UniqueName,
14
    wire::{ObjectPath, OwnedObjectPath},
15
};
16

            
17
use crate::Service;
18

            
19
const SESSION_STALE_TIMEOUT: Duration = Duration::from_secs(60);
20

            
21
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22
pub enum SessionType {
23
    X11,
24
    Wayland,
25
    Tty,
26
    Unspecified,
27
}
28

            
29
impl SessionType {
30
16
    pub fn is_graphical(self) -> bool {
31
16
        matches!(self, Self::X11 | Self::Wayland)
32
    }
33

            
34
    pub async fn from_logind(pid: u32) -> Option<Self> {
35
        let connection = zbus::Connection::system().await.ok()?;
36
        let manager = LoginManagerProxy::new(&connection).await.ok()?;
37
        let session_path = manager.get_session_by_pid(pid).await.ok()?;
38
        let session = LoginSessionProxy::builder(&connection)
39
            .path(session_path)
40
            .build()
41
            .await
42
            .ok()?;
43
        let type_str = session.type_().await.ok()?;
44
        Some(match type_str.as_str() {
45
            "x11" => Self::X11,
46
            "wayland" => Self::Wayland,
47
            "tty" => Self::Tty,
48
            _ => Self::Unspecified,
49
        })
50
    }
51

            
52
    /// Fall back to the peer's own environment, for compositors run as a
53
    /// systemd `--user` service (e.g. niri, sway), which `logind` can't
54
    /// place in a session at all. Often blocked by Yama's `ptrace_scope`,
55
    /// since the daemon isn't an ancestor of its peers; see
56
    /// [`Self::from_systemd_user_environment`] for the last resort.
57
19
    async fn from_environ(pid: u32) -> Option<Self> {
58
14
        let environ = tokio::fs::read(format!("/proc/{pid}/environ")).await.ok()?;
59
20
        Self::from_display_vars(environ.split(|&b| b == 0))
60
    }
61

            
62
    /// Last resort: the systemd `--user` manager's own exported
63
    /// environment. Systemd-integrated compositors import
64
    /// `WAYLAND_DISPLAY`/`DISPLAY` into it on startup (e.g. via
65
    /// `dbus-update-activation-environment`), and it's readable over
66
    /// D-Bus with no `ptrace_scope` restriction. Coarser than the other
67
    /// checks since it's session-wide rather than peer-specific, so it's
68
    /// only consulted once `logind` can't place the peer anywhere.
69
    async fn from_systemd_user_environment() -> Option<Self> {
70
        let connection = zbus::Connection::session().await.ok()?;
71
        let manager = SystemdManagerProxy::new(&connection).await.ok()?;
72
        let environment = manager.environment().await.ok()?;
73

            
74
        Self::from_display_vars(environment.iter().map(String::as_bytes))
75
    }
76

            
77
    /// Shared `WAYLAND_DISPLAY`/`DISPLAY` lookup over a set of `NAME=value`
78
    /// entries, as found in both `/proc/<pid>/environ` and the systemd
79
    /// `--user` manager's exported environment.
80
13
    fn from_display_vars<'a>(vars: impl Iterator<Item = &'a [u8]>) -> Option<Self> {
81
13
        let mut wayland = false;
82
13
        let mut x11 = false;
83
21
        for entry in vars {
84
33
            if let Some(value) = entry.strip_prefix(b"WAYLAND_DISPLAY=") {
85
16
                wayland |= !value.is_empty();
86
34
            } else if let Some(value) = entry.strip_prefix(b"DISPLAY=") {
87
8
                x11 |= !value.is_empty();
88
            }
89
        }
90

            
91
20
        if wayland {
92
8
            Some(Self::Wayland)
93
25
        } else if x11 {
94
8
            Some(Self::X11)
95
        } else {
96
12
            None
97
        }
98
    }
99

            
100
    /// Best-effort session type detection, cascading `logind` ->
101
    /// [`Self::from_environ`] -> [`Self::from_systemd_user_environment`].
102
    /// Stops at the first check that places the peer in a session at
103
    /// all, even a non-graphical one.
104
    pub async fn detect(pid: u32) -> Self {
105
        if let Some(session_type) = Self::from_logind(pid).await {
106
            return session_type;
107
        }
108

            
109
        if let Some(session_type) = Self::from_environ(pid).await {
110
            return session_type;
111
        }
112

            
113
        Self::from_systemd_user_environment()
114
            .await
115
            .unwrap_or(Self::Unspecified)
116
    }
117
}
118

            
119
#[zbus::proxy(
120
    default_service = "org.freedesktop.login1",
121
    interface = "org.freedesktop.login1.Manager",
122
    default_path = "/org/freedesktop/login1"
123
)]
124
trait LoginManager {
125
    #[zbus(name = "GetSessionByPID")]
126
    fn get_session_by_pid(&self, pid: u32) -> zbus::Result<OwnedObjectPath>;
127
}
128

            
129
#[zbus::proxy(
130
    default_service = "org.freedesktop.login1",
131
    interface = "org.freedesktop.login1.Session"
132
)]
133
trait LoginSession {
134
    #[zbus(property)]
135
    fn type_(&self) -> zbus::Result<String>;
136
}
137

            
138
#[zbus::proxy(
139
    default_service = "org.freedesktop.systemd1",
140
    interface = "org.freedesktop.systemd1.Manager",
141
    default_path = "/org/freedesktop/systemd1"
142
)]
143
trait SystemdManager {
144
    #[zbus(property)]
145
    fn environment(&self) -> zbus::Result<Vec<String>>;
146
}
147

            
148
#[derive(Debug, Clone)]
149
pub struct PeerInfo {
150
    pid: u32,
151
    name: String,
152
    session_type: SessionType,
153
}
154

            
155
impl PeerInfo {
156
32
    fn new(pid: u32, name: String, session_type: SessionType) -> Self {
157
        Self {
158
            pid,
159
            name,
160
            session_type,
161
        }
162
    }
163

            
164
    /// Look up the process behind a sender, and the session it runs in
165
30
    pub async fn lookup(
166
        connection: &zbus::Connection,
167
        sender: &UniqueName<'_>,
168
    ) -> Option<PeerInfo> {
169
        // p2p test clients stand for a graphical application
170
        #[cfg(any(test, feature = "test-util"))]
171
65
        if sender.as_str() == crate::service::P2P_TEST_SENDER {
172
34
            return Some(PeerInfo::new(
173
34
                std::process::id(),
174
31
                "test".to_owned(),
175
                SessionType::Wayland,
176
            ));
177
        }
178

            
179
        let proxy = zbus::fdo::DBusProxy::new(connection).await.ok()?;
180
        let pid = proxy
181
            .get_connection_unix_process_id(sender.into())
182
            .await
183
            .ok()?;
184
        let cmdline = tokio::fs::read(format!("/proc/{pid}/cmdline")).await.ok()?;
185
        let name = cmdline.split(|&b| b == 0).next()?;
186
        let name = std::path::Path::new(std::str::from_utf8(name).ok()?)
187
            .file_name()?
188
            .to_str()?
189
            .to_owned();
190
        let session_type = SessionType::detect(pid).await;
191
        Some(PeerInfo::new(pid, name, session_type))
192
    }
193

            
194
16
    pub fn session_type(&self) -> SessionType {
195
16
        self.session_type
196
    }
197
}
198

            
199
impl fmt::Display for PeerInfo {
200
4
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201
4
        write!(f, "{}[{}]", self.name, self.pid)
202
    }
203
}
204

            
205
#[derive(Clone)]
206
pub struct Session {
207
    aes_key: Option<Arc<Key>>,
208
    service: Service,
209
    path: OwnedObjectPath,
210
    sender: UniqueName<'static>,
211
    peer_info: Option<PeerInfo>,
212
    disconnected_at: Arc<Mutex<Option<Instant>>>,
213
}
214

            
215
#[interface(name = "org.freedesktop.Secret.Session")]
216
impl Session {
217
24
    pub async fn close(&self) -> Result<(), ServiceError> {
218
12
        tracing::info!("Closing session {} for {}.", self.path, self.sender);
219
12
        self.service.remove_session(&self.path).await;
220
30
        self.service
221
            .object_server()
222
6
            .remove::<Self, _>(&self.path)
223
18
            .await?;
224

            
225
6
        Ok(())
226
    }
227
}
228

            
229
impl Session {
230
33
    pub async fn new(
231
        aes_key: Option<Arc<Key>>,
232
        service: Service,
233
        sender: UniqueName<'static>,
234
        peer_info: Option<PeerInfo>,
235
    ) -> Self {
236
64
        let index = service.session_index();
237
        Self {
238
31
            path: OwnedObjectPath::try_from(format!("/org/freedesktop/secrets/session/s{index}"))
239
                .unwrap(),
240
            aes_key,
241
            service,
242
            sender,
243
            peer_info,
244
63
            disconnected_at: Arc::new(Mutex::new(None)),
245
        }
246
    }
247

            
248
14
    pub fn sender(&self) -> &UniqueName<'static> {
249
14
        &self.sender
250
    }
251

            
252
30
    pub fn peer_info(&self) -> Option<&PeerInfo> {
253
30
        self.peer_info.as_ref()
254
    }
255

            
256
30
    pub fn path(&self) -> &ObjectPath<'_> {
257
30
        &self.path
258
    }
259

            
260
17
    pub fn aes_key(&self) -> Option<Arc<Key>> {
261
17
        self.aes_key.as_ref().map(Arc::clone)
262
    }
263

            
264
16
    pub async fn mark_stale(&self) {
265
8
        *self.disconnected_at.lock().await = Some(Instant::now());
266
    }
267

            
268
60
    pub async fn unmark_stale(&self) {
269
30
        *self.disconnected_at.lock().await = None;
270
    }
271

            
272
16
    pub async fn is_stale(&self) -> bool {
273
20
        self.disconnected_at
274
            .lock()
275
12
            .await
276
12
            .is_some_and(|t| t.elapsed() > SESSION_STALE_TIMEOUT)
277
    }
278

            
279
    /// Pretend the client disconnected before the stale timeout, to test
280
    /// the cleanup without waiting for it.
281
    #[cfg(test)]
282
16
    pub(crate) async fn force_stale(&self) {
283
8
        *self.disconnected_at.lock().await =
284
12
            Some(Instant::now() - SESSION_STALE_TIMEOUT - Duration::from_secs(1));
285
    }
286

            
287
    /// Whether the client disconnected, regardless of the timeout.
288
    #[cfg(test)]
289
16
    pub(crate) async fn is_marked_stale(&self) -> bool {
290
8
        self.disconnected_at.lock().await.is_some()
291
    }
292
}
293

            
294
#[cfg(test)]
295
mod tests {
296
    use super::SessionType;
297
    use crate::tests::TestServiceSetup;
298

            
299
    /// Spawn a short-lived child process with a controlled environment, to
300
    /// exercise `SessionType::from_environ` against a real
301
    /// `/proc/<pid>/environ`.
302
    async fn spawn_with_env(vars: &[(&str, &str)]) -> std::process::Child {
303
        let mut command = std::process::Command::new("sleep");
304
        command.arg("5").env_clear();
305
        for (key, value) in vars {
306
            command.env(key, value);
307
        }
308
        let child = command.spawn().expect("failed to spawn test child process");
309
        // Poll until /proc/<pid>/environ is non-empty (it can exist
310
        // before the kernel populates it).
311
        let path = format!("/proc/{}/environ", child.id());
312
        for _ in 0..50 {
313
            if tokio::fs::read(&path)
314
                .await
315
                .is_ok_and(|buf| !buf.is_empty())
316
            {
317
                break;
318
            }
319
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
320
        }
321
        child
322
    }
323

            
324
    // Reads `/proc/<pid>/environ`
325
    #[cfg(target_os = "linux")]
326
    #[tokio::test]
327
    async fn from_environ_detects_wayland() {
328
        let mut child = spawn_with_env(&[("WAYLAND_DISPLAY", "wayland-test")]).await;
329

            
330
        let session_type = SessionType::from_environ(child.id()).await;
331

            
332
        let _ = child.kill();
333
        let _ = child.wait();
334

            
335
        assert_eq!(session_type, Some(SessionType::Wayland));
336
    }
337

            
338
    // Reads `/proc/<pid>/environ`
339
    #[cfg(target_os = "linux")]
340
    #[tokio::test]
341
    async fn from_environ_detects_x11() {
342
        let mut child = spawn_with_env(&[("DISPLAY", ":0")]).await;
343

            
344
        let session_type = SessionType::from_environ(child.id()).await;
345

            
346
        let _ = child.kill();
347
        let _ = child.wait();
348

            
349
        assert_eq!(session_type, Some(SessionType::X11));
350
    }
351

            
352
    #[tokio::test]
353
    async fn from_environ_none_without_display() {
354
        let mut child = spawn_with_env(&[]).await;
355

            
356
        let session_type = SessionType::from_environ(child.id()).await;
357

            
358
        let _ = child.kill();
359
        let _ = child.wait();
360

            
361
        assert_eq!(session_type, None);
362
    }
363

            
364
    #[test]
365
    fn from_display_vars_detects_wayland() {
366
        let vars = [b"WAYLAND_DISPLAY=wayland-test".as_slice(), b"FOO=bar"];
367

            
368
        assert_eq!(
369
            SessionType::from_display_vars(vars.into_iter()),
370
            Some(SessionType::Wayland)
371
        );
372
    }
373

            
374
    #[test]
375
    fn from_display_vars_detects_x11() {
376
        let vars = [b"DISPLAY=:0".as_slice(), b"FOO=bar"];
377

            
378
        assert_eq!(
379
            SessionType::from_display_vars(vars.into_iter()),
380
            Some(SessionType::X11)
381
        );
382
    }
383

            
384
    #[test]
385
    fn from_display_vars_prefers_wayland_over_x11() {
386
        let vars = [b"DISPLAY=:0".as_slice(), b"WAYLAND_DISPLAY=wayland-test"];
387

            
388
        assert_eq!(
389
            SessionType::from_display_vars(vars.into_iter()),
390
            Some(SessionType::Wayland)
391
        );
392
    }
393

            
394
    #[test]
395
    fn from_display_vars_ignores_empty_values() {
396
        let vars = [b"WAYLAND_DISPLAY=".as_slice(), b"DISPLAY="];
397

            
398
        assert_eq!(SessionType::from_display_vars(vars.into_iter()), None);
399
    }
400

            
401
    #[test]
402
    fn from_display_vars_none_without_display() {
403
        let vars = [b"FOO=bar".as_slice()];
404

            
405
        assert_eq!(SessionType::from_display_vars(vars.into_iter()), None);
406
    }
407

            
408
    #[tokio::test]
409
    async fn close() -> Result<(), Box<dyn std::error::Error>> {
410
        let setup = TestServiceSetup::plain_session(true).await?;
411
        let path = setup.session.inner().path().to_owned();
412

            
413
        // Verify session exists on the server
414
        let session_check = setup.server.session(&path).await;
415
        assert!(
416
            session_check.is_some(),
417
            "Session should exist on server before close"
418
        );
419

            
420
        // Close the session
421
        setup.session.close().await?;
422

            
423
        // Verify session no longer exists on the server
424
        let session_check_after = setup.server.session(&path).await;
425
        assert!(
426
            session_check_after.is_none(),
427
            "Session should not exist on server after close"
428
        );
429

            
430
        Ok(())
431
    }
432
}