feat: complete session preferences and PAM fixture gates

This commit is contained in:
2026-09-26 02:44:29 +05:30
parent 83345a1842
commit ee6186ed0b
34 changed files with 801 additions and 327 deletions

View File

@@ -4,7 +4,6 @@ use std::{io, mem, os::raw::c_char, ptr};
use crate::error::Error;
/// A live user-process record in UTMPX.
pub struct UtmpxGuard {
record: libc::utmpx,
closed: bool,

View File

@@ -14,90 +14,61 @@ use crate::{
error::{Error, ResultExt},
};
/// An account that can be offered by the login screen.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Identity {
/// Canonical username.
pub username: String,
/// Numeric user ID.
pub uid: u32,
/// Primary group ID.
pub gid: u32,
/// Home directory.
pub home: PathBuf,
/// Login shell.
pub shell: PathBuf,
}
/// Effective account state determined from the login shell and shadow aging data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccountState {
/// Account can be offered for login.
Active,
/// Password is disabled by the shadow lock marker.
Locked,
/// Password must be changed before login can continue.
PasswordExpired,
/// Account expiration date has elapsed.
AccountExpired,
/// Password inactivity period has elapsed.
AccountInactive,
/// Login shell explicitly disallows interactive sessions.
NoLoginShell,
/// Shadow data was not available or could not be parsed.
Unknown,
}
/// Non-sensitive password and account aging information.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AccountStatus {
/// Effective state used by the chooser and diagnostics.
pub state: AccountState,
/// Day the password was last changed, if present.
pub password_changed_day: Option<i64>,
/// Day the password expires, if the policy specifies one.
pub password_expiry_day: Option<i64>,
/// Day the account expires, if specified.
pub account_expiry_day: Option<i64>,
/// Day after which an expired password disables the account.
pub inactive_after_day: Option<i64>,
}
impl AccountStatus {
/// Returns whether this account may be presented as an active login choice.
pub const fn is_login_allowed(self) -> bool {
matches!(self.state, AccountState::Active)
}
}
/// An identity paired with its non-sensitive account policy state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccountRecord {
/// Discovered NSS identity.
pub identity: Identity,
/// Current local account status.
pub status: AccountStatus,
}
/// A currently logged-in process obtained from UTMPX.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActiveSession {
/// Login name associated with the session.
pub username: String,
/// UTMPX line, such as `tty2` or `pts/0`.
pub terminal: String,
/// Session leader PID when reported by UTMPX.
pub pid: libc::pid_t,
/// Remote host, if supplied by the session producer.
pub host: Option<String>,
}
/// Runtime session-management backend detected on this host.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionBackend {
/// systemd-logind runtime markers are available.
SystemdLogind,
/// UTMPX is available as a conservative fallback.
Utmpx,
}
@@ -113,15 +84,10 @@ struct ShadowEntry {
/// A non-authoritative account lockout summary.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct FaillockStatus {
/// Whether the faillock helper returned a usable result.
pub available: bool,
/// Number of observed failed attempts.
pub failures: u32,
/// Configured failure threshold, when discoverable.
pub max_tries: Option<u32>,
/// Remaining attempts before the advisory threshold.
pub remaining: Option<u32>,
/// Whether the advisory threshold has been reached.
pub locked_out: bool,
}
@@ -291,12 +257,8 @@ pub fn faillock_status(username: &str, config: &AccountsConfig) -> Result<Faillo
Ok(faillock_status_from_output(&output.stdout, max_tries))
}
/// Converts stable helper output into an advisory lockout status.
///
/// This parser accepts both the legacy `count timestamp` format and modern
/// rows containing a username prefix or timestamp columns. It intentionally
/// treats malformed output as zero failures instead of making authentication
/// fail open or fail closed.
/// Parses the legacy count format and current rows with usernames or timestamps.
/// Malformed output reports zero failures and does not control authentication.
pub fn faillock_status_from_output(output: &[u8], max_tries: Option<u32>) -> FaillockStatus {
let failures = parse_failure_count(output);
let remaining = max_tries.map(|limit| limit.saturating_sub(failures));

View File

@@ -1,8 +1,6 @@
//! Redacted security audit events.
//!
//! Audit records deliberately contain no password, token, PAM message, or
//! command-line detail. Callers can send the fields to a structured logger
//! without accidentally turning an authentication failure into a secret dump.
//! Audit records exclude secrets, PAM messages, and command arguments.
use std::fmt;
@@ -11,11 +9,8 @@ use crate::error::Error;
/// The security operation that produced an audit event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuditAction {
/// A PAM authentication attempt.
Authentication,
/// A PAM password-change transaction.
PasswordChange,
/// A user session handoff.
Session,
}
@@ -32,13 +27,9 @@ impl fmt::Display for AuditAction {
/// The outcome of a security operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuditOutcome {
/// The operation was requested.
Started,
/// The operation completed successfully.
Succeeded,
/// The operation was rejected or failed.
Failed,
/// PAM requires a password change before proceeding.
PasswordChangeRequired,
}
@@ -56,21 +47,13 @@ impl fmt::Display for AuditOutcome {
/// A safe category for a PAM failure, without exposing PAM's free-form text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PamReason {
/// Password or other authentication material was rejected.
AuthenticationRejected,
/// PAM could not reach its backing authentication service.
AuthenticationUnavailable,
/// PAM reports that the account has expired.
AccountExpired,
/// PAM requires a password change.
PasswordChangeRequired,
/// PAM reports that the retry limit was reached.
TooManyAttempts,
/// PAM conversation or token handling failed.
Conversation,
/// A PAM/system operation failed.
System,
/// An unclassified PAM status was returned.
Unknown,
}
@@ -92,18 +75,14 @@ impl fmt::Display for PamReason {
/// A structured event whose fields are safe to send to an audit logger.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AuditEvent<'a> {
/// Security operation.
pub action: AuditAction,
/// Operation outcome.
pub outcome: AuditOutcome,
/// Account name supplied by the user; never a password or token.
pub account: &'a str,
/// Sanitized PAM failure category, when applicable.
pub pam_reason: Option<PamReason>,
}
impl<'a> AuditEvent<'a> {
/// Creates an event for an operation that has just started.
pub const fn started(action: AuditAction, account: &'a str) -> Self {
Self {
action,
@@ -113,7 +92,6 @@ impl<'a> AuditEvent<'a> {
}
}
/// Creates a successful event.
pub const fn succeeded(action: AuditAction, account: &'a str) -> Self {
Self {
action,
@@ -123,7 +101,6 @@ impl<'a> AuditEvent<'a> {
}
}
/// Creates a failure event with a sanitized PAM category.
pub fn failed(action: AuditAction, account: &'a str, error: &Error) -> Self {
Self {
action,

View File

@@ -9,33 +9,20 @@ use serde::Deserialize;
use crate::error::{Error, ResultExt};
/// Validated application configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
/// Virtual terminal number used by the service.
pub tty: u8,
/// Main log file.
pub main_log_path: PathBuf,
/// Per-session log file.
pub client_log_path: PathBuf,
/// PAM service name.
pub pam_service: String,
/// Default shell used only when the account has no shell value.
pub system_shell: PathBuf,
/// Session PATH.
pub initial_path: String,
/// X11 settings.
pub x11: X11Config,
/// Wayland settings.
pub wayland: WaylandConfig,
/// Environment switcher settings.
pub environment_switcher: SwitcherConfig,
/// Power actions shown by the login screen.
pub power_controls: PowerControls,
/// Account enumeration and advisory lockout settings.
pub accounts: AccountsConfig,
/// TUI-only background, animation, and notification settings.
pub visual: VisualConfig,
}
@@ -58,21 +45,14 @@ impl Default for Config {
}
}
/// Account discovery and faillock settings.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct AccountsConfig {
/// Minimum UID shown by automatic account discovery.
pub minimum_uid: u32,
/// Usernames excluded from the chooser.
pub excluded_users: Vec<String>,
/// Whether the chooser lists NSS accounts.
pub enumerate: bool,
/// Absolute faillock helper path.
pub faillock_path: PathBuf,
/// faillock configuration used to read the deny threshold.
pub faillock_config: PathBuf,
/// Shadow database used for local password and account aging checks.
pub shadow_path: PathBuf,
}
@@ -89,21 +69,14 @@ impl Default for AccountsConfig {
}
}
/// Visual effects used only by the terminal login screen.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct VisualConfig {
/// Optional root-owned image used as a low-contrast terminal wallpaper.
pub wallpaper_path: Option<PathBuf>,
/// Enable the wallpaper and procedural background layer.
pub background_enabled: bool,
/// Advance animated background and spinner frames.
pub animations: bool,
/// Show transient in-TUI notifications for user-visible events.
pub notifications: bool,
/// Disable motion while retaining static visual styling.
pub reduced_motion: bool,
/// Maximum wallpaper file size accepted before decoding.
pub max_wallpaper_bytes: u64,
}
@@ -120,23 +93,15 @@ impl Default for VisualConfig {
}
}
/// X11 session configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct X11Config {
/// X display name.
pub display: String,
/// X server executable.
pub server_path: PathBuf,
/// Xauthority executable.
pub xauth_path: PathBuf,
/// X server startup timeout.
pub server_timeout_secs: u16,
/// X server log.
pub server_log_path: PathBuf,
/// Desktop-entry directory.
pub sessions_path: PathBuf,
/// Custom script directory.
pub scripts_path: PathBuf,
}
@@ -154,13 +119,10 @@ impl Default for X11Config {
}
}
/// Wayland session configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct WaylandConfig {
/// Desktop-entry directory.
pub sessions_path: PathBuf,
/// Custom script directory.
pub scripts_path: PathBuf,
}
@@ -173,14 +135,13 @@ impl Default for WaylandConfig {
}
}
/// Session switcher settings.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SwitcherConfig {
/// Include the fallback TTY shell in the chooser.
pub include_tty_shell: bool,
/// Maximum visible title width.
pub max_display_length: usize,
pub remember_last_session: bool,
pub last_session_path: PathBuf,
}
impl Default for SwitcherConfig {
@@ -188,29 +149,24 @@ impl Default for SwitcherConfig {
Self {
include_tty_shell: false,
max_display_length: 18,
remember_last_session: true,
last_session_path: PathBuf::from("/var/lib/latchd/last-session.toml"),
}
}
}
/// Power actions available to the login screen.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct PowerControls {
/// Built-in or administrator-defined actions.
pub entries: Vec<PowerAction>,
}
/// A power action represented as an executable argv vector.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PowerAction {
/// Displayed key, such as `F1`.
pub key: String,
/// Displayed label.
pub hint: String,
/// Executable path.
pub program: PathBuf,
/// Arguments passed without shell interpretation.
#[serde(default)]
pub args: Vec<String>,
}
@@ -287,6 +243,13 @@ pub fn validate(config: &Config) -> Result<(), Error> {
"environment_switcher.max_display_length must be greater than zero".into(),
));
}
if config.environment_switcher.remember_last_session
&& !config.environment_switcher.last_session_path.is_absolute()
{
return Err(Error::Config(
"environment_switcher.last_session_path must be absolute".into(),
));
}
for (name, path) in [
("main_log_path", &config.main_log_path),
("client_log_path", &config.client_log_path),

View File

@@ -2,47 +2,32 @@ use std::io;
use thiserror::Error;
/// The application-wide error type.
#[derive(Debug, Error)]
pub enum Error {
/// A command-line or configuration value was invalid.
#[error("configuration: {0}")]
Config(String),
/// A filesystem operation failed.
#[error("{context}: {source}")]
Io {
/// The operation being performed.
context: String,
/// The underlying error.
#[source]
source: io::Error,
},
/// TOML could not be decoded.
#[error("parse {path}: {source}")]
Toml {
/// The file being parsed.
path: String,
/// The parser error.
#[source]
source: toml::de::Error,
},
/// PAM rejected or could not complete an operation.
#[error("PAM {operation} failed with status {status}: {message}")]
Pam {
/// The PAM operation.
operation: &'static str,
/// The numeric PAM status.
status: i32,
/// The human-readable PAM message.
message: String,
},
/// A session process failed.
#[error("session: {0}")]
Session(String),
/// The terminal could not be initialized or restored.
#[error("terminal: {0}")]
Terminal(String),
/// An authentication worker request was cancelled or disconnected.
#[error("authentication worker: {0}")]
Worker(String),
}
@@ -62,7 +47,6 @@ impl Error {
}
}
/// Adds a stable operation label to an I/O error.
pub fn io_error(context: impl Into<String>, source: io::Error) -> Error {
Error::Io {
context: context.into(),
@@ -70,9 +54,7 @@ pub fn io_error(context: impl Into<String>, source: io::Error) -> Error {
}
}
/// Converts a failed result into an application error with context.
pub trait ResultExt<T> {
/// Adds context to an I/O operation.
fn io_context(self, context: impl Into<String>) -> Result<T, Error>;
}

View File

@@ -1,17 +1,11 @@
//! Core configuration, account, session, and accounting contracts for latchd.
#![deny(unsafe_op_in_unsafe_fn)]
#![warn(missing_docs)]
/// Linux UTMPX accounting primitives.
pub mod accounting;
/// NSS account discovery and faillock status.
pub mod accounts;
/// Redacted, structured security audit events.
pub mod audit;
/// Validated application configuration.
pub mod config;
/// Structured application errors.
pub mod error;
/// Session discovery and process lifecycle.
pub mod preferences;
pub mod session;

View File

@@ -0,0 +1,253 @@
//! Bounded, owner-checked persistence for last-used session choices.
use std::{
fs::{self, OpenOptions},
io::Write,
os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt},
path::Path,
time::{SystemTime, UNIX_EPOCH},
};
use serde::{Deserialize, Serialize};
use crate::{
error::{Error, ResultExt, io_error},
session::{SessionDescriptor, SessionKind},
};
const MAX_ENTRIES: usize = 128;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LastUsedEntry {
pub username: String,
pub kind: SessionKind,
pub title: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct LastUsedPreferences {
entries: Vec<LastUsedEntry>,
}
impl LastUsedPreferences {
/// Records a successful selection, moving the newest entry to the front.
pub fn remember(&mut self, username: &str, session: &SessionDescriptor) {
if username.is_empty() || session.title.is_empty() {
return;
}
self.entries.retain(|entry| entry.username != username);
self.entries.insert(
0,
LastUsedEntry {
username: username.to_owned(),
kind: session.kind,
title: session.title.clone(),
},
);
self.entries.truncate(MAX_ENTRIES);
}
/// Finds the exact previously selected session for an account.
pub fn preferred_index(&self, username: &str, sessions: &[SessionDescriptor]) -> Option<usize> {
let entry = self
.entries
.iter()
.find(|entry| entry.username == username)?;
sessions
.iter()
.position(|session| session.kind == entry.kind && session.title == entry.title)
}
pub fn entries(&self) -> &[LastUsedEntry] {
&self.entries
}
}
/// Loads preferences from an owner-checked TOML file.
pub fn load(path: &Path) -> Result<LastUsedPreferences, Error> {
if !path.is_absolute() {
return Err(Error::Config("last-session path must be absolute".into()));
}
let metadata = match fs::symlink_metadata(path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Ok(LastUsedPreferences::default());
}
Err(error) => return Err(io_error(format!("inspect {}", path.display()), error)),
};
if !trusted_file(&metadata) {
return Err(Error::Config(format!(
"last-session file must be an owner-only regular file: {}",
path.display()
)));
}
let raw = fs::read_to_string(path).io_context(format!("read {}", path.display()))?;
let preferences =
toml::from_str::<LastUsedPreferences>(&raw).map_err(|source| Error::Toml {
path: path.display().to_string(),
source,
})?;
validate(&preferences, path)?;
Ok(preferences)
}
/// Atomically saves preferences with mode `0600` under a trusted directory.
pub fn save(path: &Path, preferences: &LastUsedPreferences) -> Result<(), Error> {
if !path.is_absolute() {
return Err(Error::Config("last-session path must be absolute".into()));
}
validate(preferences, path)?;
let parent = path.parent().ok_or_else(|| {
Error::Config(format!(
"last-session path has no parent: {}",
path.display()
))
})?;
fs::create_dir_all(parent).io_context(format!("create {}", parent.display()))?;
let parent_metadata =
fs::symlink_metadata(parent).io_context(format!("inspect {}", parent.display()))?;
if !trusted_directory(&parent_metadata) {
return Err(Error::Config(format!(
"last-session directory must be owner-owned and non-writable: {}",
parent.display()
)));
}
let content = toml::to_string_pretty(preferences)
.map_err(|error| Error::Config(format!("serialize last-session preferences: {error}")))?;
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |duration| duration.as_nanos());
let temporary = parent.join(format!(
".{}.tmp.{}.{}",
path.file_name()
.and_then(|name| name.to_str())
.unwrap_or("last-session"),
std::process::id(),
nonce
));
let write_result = (|| -> Result<(), Error> {
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW)
.open(&temporary)
.io_context(format!("create {}", temporary.display()))?;
file.write_all(content.as_bytes())
.io_context(format!("write {}", temporary.display()))?;
file.sync_all()
.io_context(format!("sync {}", temporary.display()))?;
fs::rename(&temporary, path).io_context(format!("replace {}", path.display()))?;
fs::set_permissions(path, fs::Permissions::from_mode(0o600))
.io_context(format!("secure {}", path.display()))?;
Ok(())
})();
if write_result.is_err() {
let _ = fs::remove_file(&temporary);
}
write_result
}
fn validate(preferences: &LastUsedPreferences, path: &Path) -> Result<(), Error> {
if preferences.entries.len() > MAX_ENTRIES {
return Err(Error::Config(format!(
"last-session file contains more than {MAX_ENTRIES} entries: {}",
path.display()
)));
}
if preferences
.entries
.iter()
.any(|entry| entry.username.is_empty() || entry.title.is_empty())
{
return Err(Error::Config(format!(
"last-session entries must have a username and title: {}",
path.display()
)));
}
Ok(())
}
fn trusted_file(metadata: &std::fs::Metadata) -> bool {
metadata.is_file() && metadata.uid() == effective_uid() && metadata.mode() & 0o077 == 0
}
fn trusted_directory(metadata: &std::fs::Metadata) -> bool {
metadata.is_dir() && metadata.uid() == effective_uid() && metadata.mode() & 0o022 == 0
}
fn effective_uid() -> u32 {
// SAFETY: geteuid has no pointer arguments or memory preconditions.
unsafe { libc::geteuid() }
}
#[cfg(test)]
mod tests {
use super::*;
fn descriptor(kind: SessionKind, title: &str) -> SessionDescriptor {
SessionDescriptor {
kind,
title: title.into(),
argv: Vec::new(),
current_desktop: None,
session_desktop: None,
}
}
fn test_path() -> std::path::PathBuf {
std::env::temp_dir().join(format!(
"latchd-preferences-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |duration| duration.as_nanos())
))
}
#[test]
fn latest_successful_session_is_preferred_per_account() {
let wayland = descriptor(SessionKind::Wayland, "Sway");
let tty = descriptor(SessionKind::Tty, "TTY shell");
let mut preferences = LastUsedPreferences::default();
preferences.remember("alice", &wayland);
assert_eq!(
preferences.preferred_index("alice", &[tty.clone(), wayland]),
Some(1)
);
preferences.remember("alice", &tty);
assert_eq!(
preferences.preferred_index("alice", &[tty, descriptor(SessionKind::Wayland, "Sway")]),
Some(0)
);
assert_eq!(preferences.entries()[0].username, "alice");
}
#[test]
fn preferences_round_trip_atomically_with_private_permissions() {
let directory = test_path();
let path = directory.join("last-session.toml");
let session = descriptor(SessionKind::X11, "GNOME");
let mut preferences = LastUsedPreferences::default();
preferences.remember("alice", &session);
save(&path, &preferences).expect("preference save should succeed");
let loaded = load(&path).expect("preference load should succeed");
assert_eq!(loaded, preferences);
let mode = fs::symlink_metadata(&path)
.expect("preference metadata should exist")
.mode();
assert_eq!(mode & 0o077, 0);
let _ = fs::remove_dir_all(directory);
}
#[test]
fn missing_preferences_are_a_safe_empty_store() {
let path = test_path().join("missing.toml");
assert_eq!(
load(&path).expect("missing preferences are optional"),
LastUsedPreferences::default()
);
}
}

View File

@@ -26,72 +26,71 @@ use crate::{
error::{Error, ResultExt, io_error},
};
use rand::RngCore;
use serde::{Deserialize, Serialize};
use signal_hook::{consts::SIGUSR1, flag};
/// A session family supported by latchd.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SessionKind {
/// A login shell on the current virtual terminal.
Tty,
/// An X11 desktop session.
X11,
/// A Wayland desktop session.
Wayland,
}
/// A discoverable desktop or script session.
#[derive(Debug, Clone)]
pub struct SessionDescriptor {
/// Session family.
pub kind: SessionKind,
/// User-facing title.
pub title: String,
/// Program and arguments, without shell interpretation.
pub argv: Vec<String>,
/// XDG current-desktop value.
pub current_desktop: Option<String>,
/// XDG session-desktop value.
pub session_desktop: Option<String>,
}
/// A fully materialized session request.
#[derive(Debug, Clone)]
pub struct SessionSpec {
/// Session family.
pub kind: SessionKind,
/// Session title for logs.
pub title: String,
/// Program and arguments.
pub argv: Vec<String>,
/// Explicit child environment.
pub environment: Vec<(String, String)>,
/// Working directory.
pub working_directory: PathBuf,
/// Private stdout/stderr log for graphical sessions.
pub client_log_path: PathBuf,
/// Login shell for TTY fallback.
pub shell: PathBuf,
/// Virtual terminal number.
pub tty: u8,
/// X11 configuration when this is an X11 session.
pub x11: Option<X11Runtime>,
}
/// Runtime X11 parameters passed to a session.
#[derive(Debug, Clone)]
pub struct X11Runtime {
/// X display name.
pub display: String,
/// X server command.
pub server_path: PathBuf,
/// Xauthority command.
pub xauth_path: PathBuf,
/// X server timeout.
pub timeout: Duration,
/// X server log path.
pub log_path: PathBuf,
}
const PAM_SESSION_ENVIRONMENT_KEYS: [&str; 5] = [
"XDG_SESSION_CLASS",
"XDG_SESSION_TYPE",
"XDG_SESSION_DESKTOP",
"XDG_SEAT",
"XDG_VTNR",
];
impl SessionSpec {
pub fn pam_tty(&self) -> String {
format!("tty{}", self.tty)
}
/// Returns the selected-session metadata that PAM and logind must see.
pub fn pam_environment(&self) -> impl Iterator<Item = (&str, &str)> {
self.environment
.iter()
.filter(|(key, _)| PAM_SESSION_ENVIRONMENT_KEYS.contains(&key.as_str()))
.map(|(key, value)| (key.as_str(), value.as_str()))
}
}
/// Discovers configured sessions in stable directory order.
pub fn discover(config: &Config) -> Vec<SessionDescriptor> {
let mut sessions = Vec::new();
@@ -236,7 +235,6 @@ pub fn build_spec(
"XDG_RUNTIME_DIR",
format!("/run/user/{}", identity.uid),
);
insert_env(&mut environment, "XDG_SESSION_ID", "latchd".into());
insert_env(
&mut environment,
"XDG_CONFIG_HOME",
@@ -858,4 +856,40 @@ mod tests {
.all(|(key, _)| key != "DISPLAY" && key != "XAUTHORITY")
);
}
#[test]
fn selected_wayland_metadata_is_ready_for_pam() {
let identity = Identity {
username: "alice".into(),
uid: 1000,
gid: 1000,
home: "/home/alice".into(),
shell: "/bin/sh".into(),
};
let descriptor = SessionDescriptor {
kind: SessionKind::Wayland,
title: "Niri".into(),
argv: vec!["/usr/bin/niri-session".into()],
current_desktop: Some("niri".into()),
session_desktop: Some("niri".into()),
};
let spec = build_spec(&identity, &Config::default(), &descriptor).expect("valid spec");
let pam_environment = spec
.pam_environment()
.collect::<std::collections::HashMap<_, _>>();
assert_eq!(spec.pam_tty(), "tty2");
assert_eq!(pam_environment.get("XDG_SESSION_CLASS"), Some(&"user"));
assert_eq!(pam_environment.get("XDG_SESSION_TYPE"), Some(&"wayland"));
assert_eq!(pam_environment.get("XDG_SESSION_DESKTOP"), Some(&"niri"));
assert_eq!(pam_environment.get("XDG_SEAT"), Some(&"seat0"));
assert_eq!(pam_environment.get("XDG_VTNR"), Some(&"2"));
assert!(
spec.environment
.iter()
.all(|(key, _)| key != "XDG_SESSION_ID"),
"logind, not latchd, owns the session identifier"
);
}
}