Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 59c509dcbb | |||
| af5b7c8912 | |||
| 1d8921abee | |||
| 65ea523b36 | |||
| 465a19811a | |||
| 484e990c68 | |||
| 77d6994b8f | |||
| fff18bfb9d |
@@ -0,0 +1,43 @@
|
|||||||
|
# ABOUTME: Updates pkgver in moonarch-pkgbuilds after a push to main.
|
||||||
|
# ABOUTME: Ensures paru detects new versions of this package.
|
||||||
|
|
||||||
|
name: Update PKGBUILD version
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
update-pkgver:
|
||||||
|
runs-on: moonarch
|
||||||
|
steps:
|
||||||
|
- name: Checkout source repo
|
||||||
|
run: |
|
||||||
|
git clone --bare http://gitea:3000/nevaforget/moonlock.git source.git
|
||||||
|
cd source.git
|
||||||
|
PKGVER=$(git describe --long --tags | sed 's/^v//;s/-/.r/;s/-/./')
|
||||||
|
echo "New pkgver: $PKGVER"
|
||||||
|
echo "$PKGVER" > /tmp/pkgver
|
||||||
|
|
||||||
|
- name: Update PKGBUILD
|
||||||
|
run: |
|
||||||
|
PKGVER=$(cat /tmp/pkgver)
|
||||||
|
git clone http://gitea:3000/nevaforget/moonarch-pkgbuilds.git pkgbuilds
|
||||||
|
cd pkgbuilds
|
||||||
|
|
||||||
|
OLD_VER=$(grep '^pkgver=' moonlock-git/PKGBUILD | cut -d= -f2)
|
||||||
|
if [ "$OLD_VER" = "$PKGVER" ]; then
|
||||||
|
echo "pkgver already up to date ($PKGVER)"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
sed -i "s/^pkgver=.*/pkgver=$PKGVER/" moonlock-git/PKGBUILD
|
||||||
|
sed -i "s/^\tpkgver = .*/\tpkgver = $PKGVER/" moonlock-git/.SRCINFO
|
||||||
|
echo "Updated pkgver: $OLD_VER → $PKGVER"
|
||||||
|
|
||||||
|
git config user.name "pkgver-bot"
|
||||||
|
git config user.email "gitea@moonarch.de"
|
||||||
|
git add moonlock-git/PKGBUILD moonlock-git/.SRCINFO
|
||||||
|
git commit -m "chore(moonlock-git): bump pkgver to $PKGVER"
|
||||||
|
git -c http.extraHeader="Authorization: token ${{ secrets.PKGBUILD_TOKEN }}" push
|
||||||
@@ -19,7 +19,7 @@ Teil des Moonarch-Ökosystems.
|
|||||||
## Projektstruktur
|
## Projektstruktur
|
||||||
|
|
||||||
- `src/` — Rust-Quellcode (main.rs, lockscreen.rs, auth.rs, fingerprint.rs, config.rs, i18n.rs, users.rs, power.rs)
|
- `src/` — Rust-Quellcode (main.rs, lockscreen.rs, auth.rs, fingerprint.rs, config.rs, i18n.rs, users.rs, power.rs)
|
||||||
- `resources/` — GResource-Assets (style.css, wallpaper.jpg, default-avatar.svg)
|
- `resources/` — GResource-Assets (style.css, default-avatar.svg)
|
||||||
- `config/` — PAM-Konfiguration und Beispiel-Config
|
- `config/` — PAM-Konfiguration und Beispiel-Config
|
||||||
|
|
||||||
## Kommandos
|
## Kommandos
|
||||||
@@ -37,14 +37,14 @@ LD_PRELOAD=/usr/lib/libgtk4-layer-shell.so ./target/release/moonlock
|
|||||||
|
|
||||||
## Architektur
|
## Architektur
|
||||||
|
|
||||||
- `auth.rs` — PAM-Authentifizierung via Raw FFI (unsafe extern "C" conv callback, msg_style-aware, Zeroizing<Vec<u8>>)
|
- `auth.rs` — PAM-Authentifizierung via Raw FFI (unsafe extern "C" conv callback, msg_style-aware, Zeroizing<CString>), check_account() für pam_acct_mgmt-Only-Checks nach Fingerprint-Unlock
|
||||||
- `fingerprint.rs` — fprintd D-Bus Listener, async init/claim/verify via gio futures, sender-validated signal handler, cleanup_dbus() für sauberen D-Bus-Lifecycle, running_flag für Race-Safety in async restarts, on_exhausted callback after MAX_FP_ATTEMPTS
|
- `fingerprint.rs` — fprintd D-Bus Listener, async init/claim/verify via gio futures, sender-validated signal handler, cleanup_dbus() für sauberen D-Bus-Lifecycle, running_flag für Race-Safety in async restarts, on_exhausted callback after MAX_FP_ATTEMPTS, resume_async() für Neustart nach transientem Fehler (mit failed_attempts-Reset und Signal-Handler-Cleanup)
|
||||||
- `users.rs` — Aktuellen User via nix getuid, Avatar-Loading mit Symlink-Rejection
|
- `users.rs` — Aktuellen User via nix getuid, Avatar-Loading mit Symlink-Rejection
|
||||||
- `power.rs` — Reboot/Shutdown via /usr/bin/systemctl
|
- `power.rs` — Reboot/Shutdown via /usr/bin/systemctl
|
||||||
- `i18n.rs` — Locale-Erkennung (OnceLock-cached) und String-Tabellen (DE/EN), faillock_warning mit konfigurierbarem max_attempts
|
- `i18n.rs` — Locale-Erkennung (OnceLock-cached) und String-Tabellen (DE/EN), faillock_warning mit konfigurierbarem max_attempts
|
||||||
- `config.rs` — TOML-Config (background_path, background_blur, fingerprint_enabled als Option<bool>) + Wallpaper-Fallback + Symlink-Rejection für background_path + Parse-Error-Logging
|
- `config.rs` — TOML-Config (background_path, background_blur clamped [0,100], fingerprint_enabled als Option<bool>) + Wallpaper-Fallback + Symlink-Rejection via symlink_metadata + Parse-Error-Logging
|
||||||
- `lockscreen.rs` — GTK4 UI via LockscreenHandles, PAM-Auth via gio::spawn_blocking, FP-Label/Start separat verdrahtet, Zeroizing<String> für Passwort, Power-Confirm, GPU-Blur via GskBlurNode, Blur/Avatar-Cache für Multi-Monitor
|
- `lockscreen.rs` — GTK4 UI via LockscreenHandles, PAM-Auth via gio::spawn_blocking mit 30s Timeout und Generation Counter, FP-Label/Start separat verdrahtet mit pam_acct_mgmt-Check und auto-resume, Zeroizing<String> für Passwort, Power-Confirm, GPU-Blur via GskBlurNode (Downscale auf max 1920px), Blur/Avatar-Cache für Multi-Monitor
|
||||||
- `main.rs` — Entry Point, Panic-Hook (vor Logging), Root-Check, ext-session-lock-v1 (Pflicht in Release), Multi-Monitor mit shared Blur/Avatar-Caches, systemd-Journal-Logging, Debug-Level per `MOONLOCK_DEBUG` Env-Var, async fprintd-Init nach window.present()
|
- `main.rs` — Entry Point, Panic-Hook (vor Logging), Root-Check, ext-session-lock-v1 (Pflicht in Release), Multi-Monitor mit shared Blur/Avatar-Caches, systemd-Journal-Logging, Debug-Level per `MOONLOCK_DEBUG` Env-Var, async fprintd-Init nach window.present(), Wallpaper-Laden nach lock()
|
||||||
|
|
||||||
## Sicherheit
|
## Sicherheit
|
||||||
|
|
||||||
@@ -53,7 +53,10 @@ LD_PRELOAD=/usr/lib/libgtk4-layer-shell.so ./target/release/moonlock
|
|||||||
- Panic-Hook: Bei Crash wird geloggt, aber NIEMALS unlock() aufgerufen — Screen bleibt schwarz. Hook wird vor Logging installiert.
|
- Panic-Hook: Bei Crash wird geloggt, aber NIEMALS unlock() aufgerufen — Screen bleibt schwarz. Hook wird vor Logging installiert.
|
||||||
- PAM-Callback: msg_style-aware (Passwort nur bei PAM_PROMPT_ECHO_OFF), strdup-OOM-sicher, num_msg-Guard gegen negative Werte
|
- PAM-Callback: msg_style-aware (Passwort nur bei PAM_PROMPT_ECHO_OFF), strdup-OOM-sicher, num_msg-Guard gegen negative Werte
|
||||||
- fprintd: D-Bus Signal-Sender wird gegen fprintd's unique bus name validiert (Anti-Spoofing)
|
- fprintd: D-Bus Signal-Sender wird gegen fprintd's unique bus name validiert (Anti-Spoofing)
|
||||||
- Passwort: Zeroizing<String> ab GTK-Entry-Extraktion, Zeroizing<Vec<u8>> im PAM-FFI-Layer (bekannte Einschränkung: GLib-GString und CString werden nicht gezeroized — inhärente GTK/libc-Limitierung)
|
- Passwort: Zeroizing<String> ab GTK-Entry-Extraktion, Zeroizing<CString> im PAM-FFI-Layer (bekannte Einschränkung: GLib-GString und strdup-Kopie in PAM werden nicht gezeroized — inhärente GTK/libc-Limitierung)
|
||||||
|
- Fingerprint-Unlock: pam_acct_mgmt-Check nach verify-match erzwingt Account-Policies (Lockout, Ablauf), resume_async() startet FP bei transientem Fehler neu (mit failed_attempts-Reset und Signal-Handler-Cleanup)
|
||||||
|
- Wallpaper wird nach lock() geladen — Disk-I/O verzögert nicht die Lock-Akquisition
|
||||||
|
- PAM-Timeout: 30s Timeout verhindert permanentes Aussperren bei hängenden PAM-Modulen, Generation Counter verhindert Interferenz paralleler Auth-Versuche
|
||||||
- Root-Check: Exit mit Fehler wenn als root gestartet
|
- Root-Check: Exit mit Fehler wenn als root gestartet
|
||||||
- Faillock: UI-Warnung nach 3 Fehlversuchen, aber PAM entscheidet über Lockout (Entry bleibt aktiv)
|
- Faillock: UI-Warnung nach 3 Fehlversuchen, aber PAM entscheidet über Lockout (Entry bleibt aktiv)
|
||||||
- Kein Schließen per Escape/Alt-F4 — nur durch erfolgreiche PAM-Auth oder Fingerprint
|
- Kein Schließen per Escape/Alt-F4 — nur durch erfolgreiche PAM-Auth oder Fingerprint
|
||||||
|
|||||||
Generated
+1
-1
@@ -575,7 +575,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "moonlock"
|
name = "moonlock"
|
||||||
version = "0.6.0"
|
version = "0.6.7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"gdk-pixbuf",
|
"gdk-pixbuf",
|
||||||
"gdk4",
|
"gdk4",
|
||||||
|
|||||||
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "moonlock"
|
name = "moonlock"
|
||||||
version = "0.6.1"
|
version = "0.6.7"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
description = "A secure Wayland lockscreen with GTK4, PAM and fingerprint support"
|
description = "A secure Wayland lockscreen with GTK4, PAM and fingerprint support"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
@@ -16,7 +16,7 @@ toml = "0.8"
|
|||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
graphene-rs = { version = "0.22", package = "graphene-rs" }
|
graphene-rs = { version = "0.22", package = "graphene-rs" }
|
||||||
nix = { version = "0.29", features = ["user"] }
|
nix = { version = "0.29", features = ["user"] }
|
||||||
zeroize = { version = "1", features = ["derive"] }
|
zeroize = { version = "1", features = ["derive", "std"] }
|
||||||
libc = "0.2"
|
libc = "0.2"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
systemd-journal-logger = "2.2"
|
systemd-journal-logger = "2.2"
|
||||||
|
|||||||
@@ -2,6 +2,27 @@
|
|||||||
|
|
||||||
Architectural and design decisions for Moonlock, in reverse chronological order.
|
Architectural and design decisions for Moonlock, in reverse chronological order.
|
||||||
|
|
||||||
|
## 2026-03-30 – Third audit: blur offset, lock-before-IO, FP signal lifecycle, TOCTOU
|
||||||
|
|
||||||
|
- **Who**: Nyx, Dom
|
||||||
|
- **Why**: Third triple audit (quality, performance, security) found: blur padding offset rendering texture at (0,0) instead of (-pad,-pad) causing edge darkening on left/top (BUG), wallpaper disk I/O blocking before lock() extending the unsecured window (PERF/SEC), signal handler duplication on resume_async (SEC), failed_attempts not reset on FP resume (SEC), unknown VerifyStatus with done=false hanging FP listener (SEC), TOCTOU in is_file+is_symlink checks (SEC), dead code in faillock_warning (QUALITY), unbounded blur sigma (SEC).
|
||||||
|
- **Tradeoffs**: Wallpaper loads after lock() — screen briefly shows without wallpaper until texture is ready. Acceptable: security > aesthetics. Blur sigma clamped to [0.0, 100.0] — arbitrary upper bound but prevents GPU memory exhaustion.
|
||||||
|
- **How**: (1) Texture offset to (-pad, -pad) in render_blurred_texture. (2) lock.lock() before resolve_background_path. (3) begin_verification disconnects old signal_id before registering new. (4) resume_async resets failed_attempts. (5) Unknown VerifyStatus with done=true triggers restart. (6) symlink_metadata() for atomic file+symlink check. (7) faillock_warning dead code removed, saturating_sub. (8) background_blur clamped. (9) Redundant Zeroizing<Vec<u8>> removed. (10) Default impl for FingerprintListener. (11) on_verify_status restricted to pub(crate). (12) Warn logging for non-UTF-8 GECOS and avatar paths.
|
||||||
|
|
||||||
|
## 2026-03-30 – Second audit: zeroize CString, FP account check, PAM timeout, blur downscale
|
||||||
|
|
||||||
|
- **Who**: Nyx, Dom
|
||||||
|
- **Why**: Second triple audit (quality, performance, security) found: CString password copy not zeroized (HIGH), fingerprint unlock bypassing pam_acct_mgmt (MEDIUM), no PAM timeout leaving user locked out on hanging modules (MEDIUM), GPU blur on full wallpaper resolution (MEDIUM), no-monitor edge case doing `return` instead of `exit(1)` (MEDIUM).
|
||||||
|
- **Tradeoffs**: PAM timeout (30s) uses a generation counter to avoid stale result interference — adds complexity but prevents parallel PAM sessions. FP restart after failed account check re-claims the device, adding a D-Bus round-trip, but prevents permanent FP death on transient failures. Blur downscale to 1920px cap trades negligible quality for ~4x less GPU work on 4K wallpapers.
|
||||||
|
- **How**: (1) `Zeroizing<CString>` wraps password in auth.rs, `zeroize/std` feature enabled. (2) `check_account()` calls pam_acct_mgmt after FP match; `resume_async()` restarts FP on transient failure. (3) `auth_generation` counter invalidates stale PAM results; 30s timeout re-enables UI. (4) `MAX_BLUR_DIMENSION` caps blur input at 1920px, sigma scaled proportionally. (5) `exit(1)` on no-monitor after `lock.lock()`.
|
||||||
|
|
||||||
|
## 2026-03-28 – Remove embedded wallpaper from binary
|
||||||
|
|
||||||
|
- **Who**: Nyx, Dom
|
||||||
|
- **Why**: Wallpaper is installed by moonarch to /usr/share/moonarch/wallpaper.jpg. Embedding a 374K JPEG in the binary is redundant. GTK background color (Catppuccin Mocha base) is a clean fallback.
|
||||||
|
- **Tradeoffs**: Without moonarch installed AND without config, lockscreen shows plain dark background instead of wallpaper. Acceptable — that's the expected minimal state.
|
||||||
|
- **How**: Remove wallpaper.jpg from GResources, return None from resolve_background_path when no file found, skip background picture creation when no texture available.
|
||||||
|
|
||||||
## 2026-03-28 – Audit-driven security and lifecycle fixes (v0.6.0)
|
## 2026-03-28 – Audit-driven security and lifecycle fixes (v0.6.0)
|
||||||
|
|
||||||
- **Who**: Nyx, Dom
|
- **Who**: Nyx, Dom
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
<gresources>
|
<gresources>
|
||||||
<gresource prefix="/dev/moonarch/moonlock">
|
<gresource prefix="/dev/moonarch/moonlock">
|
||||||
<file>style.css</file>
|
<file>style.css</file>
|
||||||
<file>wallpaper.jpg</file>
|
|
||||||
<file>default-avatar.svg</file>
|
<file>default-avatar.svg</file>
|
||||||
</gresource>
|
</gresource>
|
||||||
</gresources>
|
</gresources>
|
||||||
|
|||||||
+1
-1
@@ -23,7 +23,7 @@ window.lockscreen.visible {
|
|||||||
|
|
||||||
/* Round avatar image */
|
/* Round avatar image */
|
||||||
.avatar {
|
.avatar {
|
||||||
border-radius: 50%;
|
border-radius: 9999px;
|
||||||
min-width: 128px;
|
min-width: 128px;
|
||||||
min-height: 128px;
|
min-height: 128px;
|
||||||
background-color: @theme_selected_bg_color;
|
background-color: @theme_selected_bg_color;
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 366 KiB |
+61
-5
@@ -149,10 +149,9 @@ unsafe extern "C" fn pam_conv_callback(
|
|||||||
/// Returns true on success, false on authentication failure.
|
/// Returns true on success, false on authentication failure.
|
||||||
/// The password is wiped from memory after use via zeroize.
|
/// The password is wiped from memory after use via zeroize.
|
||||||
pub fn authenticate(username: &str, password: &str) -> bool {
|
pub fn authenticate(username: &str, password: &str) -> bool {
|
||||||
// Use Zeroizing to ensure password bytes are wiped on drop
|
// CString::new takes ownership of the Vec — Zeroizing<CString> wipes on drop
|
||||||
let password_bytes = Zeroizing::new(password.as_bytes().to_vec());
|
let password_cstr = match CString::new(password.as_bytes().to_vec()) {
|
||||||
let password_cstr = match CString::new(password_bytes.as_slice()) {
|
Ok(c) => Zeroizing::new(c),
|
||||||
Ok(c) => c,
|
|
||||||
Err(_) => return false, // Password contains null byte
|
Err(_) => return false, // Password contains null byte
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -168,7 +167,7 @@ pub fn authenticate(username: &str, password: &str) -> bool {
|
|||||||
|
|
||||||
let conv = PamConv {
|
let conv = PamConv {
|
||||||
conv: pam_conv_callback,
|
conv: pam_conv_callback,
|
||||||
appdata_ptr: &password_cstr as *const CString as *mut libc::c_void,
|
appdata_ptr: std::ptr::from_ref::<CString>(&password_cstr) as *mut libc::c_void,
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut handle: *mut libc::c_void = ptr::null_mut();
|
let mut handle: *mut libc::c_void = ptr::null_mut();
|
||||||
@@ -207,6 +206,51 @@ pub fn authenticate(username: &str, password: &str) -> bool {
|
|||||||
acct_ret == PAM_SUCCESS
|
acct_ret == PAM_SUCCESS
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Check account restrictions via PAM without authentication.
|
||||||
|
///
|
||||||
|
/// Used after fingerprint unlock to enforce account policies (lockout, expiry)
|
||||||
|
/// that would otherwise be bypassed when not going through pam_authenticate.
|
||||||
|
/// Returns true if the account is valid and allowed to log in.
|
||||||
|
pub fn check_account(username: &str) -> bool {
|
||||||
|
let service = match CString::new("moonlock") {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(_) => return false,
|
||||||
|
};
|
||||||
|
|
||||||
|
let username_cstr = match CString::new(username) {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(_) => return false,
|
||||||
|
};
|
||||||
|
|
||||||
|
// No password needed — we only check account status, not authenticate.
|
||||||
|
// PAM conv callback is required by pam_start but won't be called for acct_mgmt.
|
||||||
|
let empty_password = Zeroizing::new(CString::new("").unwrap());
|
||||||
|
let conv = PamConv {
|
||||||
|
conv: pam_conv_callback,
|
||||||
|
appdata_ptr: std::ptr::from_ref::<CString>(&empty_password) as *mut libc::c_void,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut handle: *mut libc::c_void = ptr::null_mut();
|
||||||
|
|
||||||
|
let ret = unsafe {
|
||||||
|
pam_start(
|
||||||
|
service.as_ptr(),
|
||||||
|
username_cstr.as_ptr(),
|
||||||
|
&conv,
|
||||||
|
&mut handle,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
if ret != PAM_SUCCESS || handle.is_null() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let acct_ret = unsafe { pam_acct_mgmt(handle, 0) };
|
||||||
|
unsafe { pam_end(handle, acct_ret) };
|
||||||
|
|
||||||
|
acct_ret == PAM_SUCCESS
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -241,4 +285,16 @@ mod tests {
|
|||||||
let result = authenticate("", "password");
|
let result = authenticate("", "password");
|
||||||
assert!(!result);
|
assert!(!result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn check_account_empty_username_fails() {
|
||||||
|
let result = check_account("");
|
||||||
|
assert!(!result);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn check_account_null_byte_username_fails() {
|
||||||
|
let result = check_account("user\0name");
|
||||||
|
assert!(!result);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+15
-12
@@ -6,7 +6,6 @@ use std::fs;
|
|||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
const MOONARCH_WALLPAPER: &str = "/usr/share/moonarch/wallpaper.jpg";
|
const MOONARCH_WALLPAPER: &str = "/usr/share/moonarch/wallpaper.jpg";
|
||||||
const GRESOURCE_PREFIX: &str = "/dev/moonarch/moonlock";
|
|
||||||
|
|
||||||
fn default_config_paths() -> Vec<PathBuf> {
|
fn default_config_paths() -> Vec<PathBuf> {
|
||||||
let mut paths = vec![PathBuf::from("/etc/moonlock/moonlock.toml")];
|
let mut paths = vec![PathBuf::from("/etc/moonlock/moonlock.toml")];
|
||||||
@@ -52,7 +51,9 @@ pub fn load_config(config_paths: Option<&[PathBuf]>) -> Config {
|
|||||||
match toml::from_str::<RawConfig>(&content) {
|
match toml::from_str::<RawConfig>(&content) {
|
||||||
Ok(parsed) => {
|
Ok(parsed) => {
|
||||||
if parsed.background_path.is_some() { merged.background_path = parsed.background_path; }
|
if parsed.background_path.is_some() { merged.background_path = parsed.background_path; }
|
||||||
if parsed.background_blur.is_some() { merged.background_blur = parsed.background_blur; }
|
if let Some(blur) = parsed.background_blur {
|
||||||
|
merged.background_blur = Some(blur.clamp(0.0, 100.0));
|
||||||
|
}
|
||||||
if let Some(fp) = parsed.fingerprint_enabled { merged.fingerprint_enabled = fp; }
|
if let Some(fp) = parsed.fingerprint_enabled { merged.fingerprint_enabled = fp; }
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -64,17 +65,19 @@ pub fn load_config(config_paths: Option<&[PathBuf]>) -> Config {
|
|||||||
merged
|
merged
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn resolve_background_path(config: &Config) -> PathBuf {
|
pub fn resolve_background_path(config: &Config) -> Option<PathBuf> {
|
||||||
resolve_background_path_with(config, Path::new(MOONARCH_WALLPAPER))
|
resolve_background_path_with(config, Path::new(MOONARCH_WALLPAPER))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn resolve_background_path_with(config: &Config, moonarch_wallpaper: &Path) -> PathBuf {
|
pub fn resolve_background_path_with(config: &Config, moonarch_wallpaper: &Path) -> Option<PathBuf> {
|
||||||
if let Some(ref bg) = config.background_path {
|
if let Some(ref bg) = config.background_path {
|
||||||
let path = PathBuf::from(bg);
|
let path = PathBuf::from(bg);
|
||||||
if path.is_file() && !path.is_symlink() { return path; }
|
if let Ok(meta) = path.symlink_metadata() {
|
||||||
|
if meta.is_file() && !meta.file_type().is_symlink() { return Some(path); }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if moonarch_wallpaper.is_file() { return moonarch_wallpaper.to_path_buf(); }
|
if moonarch_wallpaper.is_file() { return Some(moonarch_wallpaper.to_path_buf()); }
|
||||||
PathBuf::from(format!("{GRESOURCE_PREFIX}/wallpaper.jpg"))
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -109,7 +112,7 @@ mod tests {
|
|||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
let wp = dir.path().join("bg.jpg"); fs::write(&wp, "fake").unwrap();
|
let wp = dir.path().join("bg.jpg"); fs::write(&wp, "fake").unwrap();
|
||||||
let c = Config { background_path: Some(wp.to_str().unwrap().to_string()), ..Config::default() };
|
let c = Config { background_path: Some(wp.to_str().unwrap().to_string()), ..Config::default() };
|
||||||
assert_eq!(resolve_background_path_with(&c, Path::new("/nonexistent")), wp);
|
assert_eq!(resolve_background_path_with(&c, Path::new("/nonexistent")), Some(wp));
|
||||||
}
|
}
|
||||||
#[test] fn empty_user_config_preserves_system_fingerprint() {
|
#[test] fn empty_user_config_preserves_system_fingerprint() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
@@ -120,10 +123,10 @@ mod tests {
|
|||||||
let c = load_config(Some(&[sys_conf, usr_conf]));
|
let c = load_config(Some(&[sys_conf, usr_conf]));
|
||||||
assert!(!c.fingerprint_enabled);
|
assert!(!c.fingerprint_enabled);
|
||||||
}
|
}
|
||||||
#[test] fn resolve_gresource_fallback() {
|
#[test] fn resolve_no_wallpaper_returns_none() {
|
||||||
let c = Config::default();
|
let c = Config::default();
|
||||||
let r = resolve_background_path_with(&c, Path::new("/nonexistent"));
|
let r = resolve_background_path_with(&c, Path::new("/nonexistent"));
|
||||||
assert!(r.to_str().unwrap().contains("moonlock"));
|
assert!(r.is_none());
|
||||||
}
|
}
|
||||||
#[test] fn toml_parse_error_returns_default() {
|
#[test] fn toml_parse_error_returns_default() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
@@ -141,8 +144,8 @@ mod tests {
|
|||||||
fs::write(&real, "fake").unwrap();
|
fs::write(&real, "fake").unwrap();
|
||||||
std::os::unix::fs::symlink(&real, &link).unwrap();
|
std::os::unix::fs::symlink(&real, &link).unwrap();
|
||||||
let c = Config { background_path: Some(link.to_str().unwrap().to_string()), ..Config::default() };
|
let c = Config { background_path: Some(link.to_str().unwrap().to_string()), ..Config::default() };
|
||||||
// Symlink should be rejected — falls through to moonarch wallpaper or gresource
|
// Symlink should be rejected — falls through to None
|
||||||
let r = resolve_background_path_with(&c, Path::new("/nonexistent"));
|
let r = resolve_background_path_with(&c, Path::new("/nonexistent"));
|
||||||
assert_ne!(r, link);
|
assert!(r.is_none());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+54
-13
@@ -13,6 +13,7 @@ const FPRINTD_DEVICE_IFACE: &str = "net.reactivated.Fprint.Device";
|
|||||||
|
|
||||||
const MAX_FP_ATTEMPTS: u32 = 10;
|
const MAX_FP_ATTEMPTS: u32 = 10;
|
||||||
const DBUS_TIMEOUT_MS: i32 = 3000;
|
const DBUS_TIMEOUT_MS: i32 = 3000;
|
||||||
|
const FPRINTD_DEVICE_PREFIX: &str = "/net/reactivated/Fprint/Device/";
|
||||||
|
|
||||||
/// Retry-able statuses — finger not read properly, try again.
|
/// Retry-able statuses — finger not read properly, try again.
|
||||||
const RETRY_STATUSES: &[&str] = &[
|
const RETRY_STATUSES: &[&str] = &[
|
||||||
@@ -35,10 +36,8 @@ pub struct FingerprintListener {
|
|||||||
on_exhausted: Option<Box<dyn Fn() + 'static>>,
|
on_exhausted: Option<Box<dyn Fn() + 'static>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FingerprintListener {
|
impl Default for FingerprintListener {
|
||||||
/// Create a lightweight FingerprintListener without any D-Bus calls.
|
fn default() -> Self {
|
||||||
/// Call `init_async().await` afterwards to connect to fprintd.
|
|
||||||
pub fn new() -> Self {
|
|
||||||
FingerprintListener {
|
FingerprintListener {
|
||||||
device_proxy: None,
|
device_proxy: None,
|
||||||
signal_id: None,
|
signal_id: None,
|
||||||
@@ -50,6 +49,14 @@ impl FingerprintListener {
|
|||||||
on_exhausted: None,
|
on_exhausted: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FingerprintListener {
|
||||||
|
/// Create a lightweight FingerprintListener without any D-Bus calls.
|
||||||
|
/// Call `init_async().await` afterwards to connect to fprintd.
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
/// Connect to fprintd and get the default device asynchronously.
|
/// Connect to fprintd and get the default device asynchronously.
|
||||||
pub async fn init_async(&mut self) {
|
pub async fn init_async(&mut self) {
|
||||||
@@ -93,6 +100,10 @@ impl FingerprintListener {
|
|||||||
if device_path.is_empty() {
|
if device_path.is_empty() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if !device_path.starts_with(FPRINTD_DEVICE_PREFIX) {
|
||||||
|
log::warn!("Unexpected fprintd device path: {device_path}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
match gio::DBusProxy::for_bus_future(
|
match gio::DBusProxy::for_bus_future(
|
||||||
gio::BusType::System,
|
gio::BusType::System,
|
||||||
@@ -154,14 +165,6 @@ impl FingerprintListener {
|
|||||||
G: Fn() + 'static,
|
G: Fn() + 'static,
|
||||||
H: Fn() + 'static,
|
H: Fn() + 'static,
|
||||||
{
|
{
|
||||||
let proxy = {
|
|
||||||
let inner = listener.borrow();
|
|
||||||
match inner.device_proxy.clone() {
|
|
||||||
Some(p) => p,
|
|
||||||
None => return,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
{
|
{
|
||||||
let mut inner = listener.borrow_mut();
|
let mut inner = listener.borrow_mut();
|
||||||
inner.on_success = Some(Box::new(on_success));
|
inner.on_success = Some(Box::new(on_success));
|
||||||
@@ -169,6 +172,39 @@ impl FingerprintListener {
|
|||||||
inner.on_exhausted = Some(Box::new(on_exhausted));
|
inner.on_exhausted = Some(Box::new(on_exhausted));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Self::begin_verification(listener, username).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resume fingerprint verification after a transient interruption (e.g. failed
|
||||||
|
/// PAM account check). Reuses previously stored callbacks. Re-claims the device
|
||||||
|
/// and restarts verification from scratch.
|
||||||
|
pub async fn resume_async(
|
||||||
|
listener: &Rc<RefCell<FingerprintListener>>,
|
||||||
|
username: &str,
|
||||||
|
) {
|
||||||
|
listener.borrow_mut().failed_attempts = 0;
|
||||||
|
Self::begin_verification(listener, username).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Claim device, start verification, and connect D-Bus signal handler.
|
||||||
|
/// Assumes device_proxy is set and callbacks are already stored.
|
||||||
|
async fn begin_verification(
|
||||||
|
listener: &Rc<RefCell<FingerprintListener>>,
|
||||||
|
username: &str,
|
||||||
|
) {
|
||||||
|
let proxy = {
|
||||||
|
let mut inner = listener.borrow_mut();
|
||||||
|
let proxy = match inner.device_proxy.clone() {
|
||||||
|
Some(p) => p,
|
||||||
|
None => return,
|
||||||
|
};
|
||||||
|
// Disconnect any previous signal handler to prevent duplicates on resume
|
||||||
|
if let Some(old_id) = inner.signal_id.take() {
|
||||||
|
proxy.disconnect(old_id);
|
||||||
|
}
|
||||||
|
proxy
|
||||||
|
};
|
||||||
|
|
||||||
// Claim the device
|
// Claim the device
|
||||||
let args = glib::Variant::from((&username,));
|
let args = glib::Variant::from((&username,));
|
||||||
if let Err(e) = proxy
|
if let Err(e) = proxy
|
||||||
@@ -246,7 +282,7 @@ impl FingerprintListener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Process a VerifyStatus signal from fprintd.
|
/// Process a VerifyStatus signal from fprintd.
|
||||||
pub fn on_verify_status(&mut self, status: &str, done: bool) {
|
pub(crate) fn on_verify_status(&mut self, status: &str, done: bool) {
|
||||||
if !self.running {
|
if !self.running {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -286,6 +322,9 @@ impl FingerprintListener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
log::debug!("Unhandled fprintd status: {status}");
|
log::debug!("Unhandled fprintd status: {status}");
|
||||||
|
if done {
|
||||||
|
self.restart_verify_async();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Restart fingerprint verification asynchronously after a completed attempt.
|
/// Restart fingerprint verification asynchronously after a completed attempt.
|
||||||
@@ -384,11 +423,13 @@ mod tests {
|
|||||||
let called_clone = called.clone();
|
let called_clone = called.clone();
|
||||||
let mut listener = FingerprintListener::new();
|
let mut listener = FingerprintListener::new();
|
||||||
listener.running = true;
|
listener.running = true;
|
||||||
|
listener.running_flag.set(true);
|
||||||
listener.on_failure = Some(Box::new(move || { called_clone.set(true); }));
|
listener.on_failure = Some(Box::new(move || { called_clone.set(true); }));
|
||||||
|
|
||||||
listener.on_verify_status("verify-no-match", false);
|
listener.on_verify_status("verify-no-match", false);
|
||||||
assert!(called.get());
|
assert!(called.get());
|
||||||
assert!(listener.running);
|
assert!(listener.running);
|
||||||
|
assert!(listener.running_flag.get());
|
||||||
assert_eq!(listener.failed_attempts, 1);
|
assert_eq!(listener.failed_attempts, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+39
-5
@@ -28,6 +28,7 @@ pub struct Strings {
|
|||||||
pub confirm_no: &'static str,
|
pub confirm_no: &'static str,
|
||||||
pub faillock_attempts_remaining: &'static str,
|
pub faillock_attempts_remaining: &'static str,
|
||||||
pub faillock_locked: &'static str,
|
pub faillock_locked: &'static str,
|
||||||
|
pub auth_timeout: &'static str,
|
||||||
}
|
}
|
||||||
|
|
||||||
const STRINGS_DE: Strings = Strings {
|
const STRINGS_DE: Strings = Strings {
|
||||||
@@ -46,6 +47,7 @@ const STRINGS_DE: Strings = Strings {
|
|||||||
confirm_no: "Abbrechen",
|
confirm_no: "Abbrechen",
|
||||||
faillock_attempts_remaining: "Noch {n} Versuch(e) vor Kontosperrung!",
|
faillock_attempts_remaining: "Noch {n} Versuch(e) vor Kontosperrung!",
|
||||||
faillock_locked: "Konto ist möglicherweise gesperrt",
|
faillock_locked: "Konto ist möglicherweise gesperrt",
|
||||||
|
auth_timeout: "Authentifizierung abgelaufen — bitte erneut versuchen",
|
||||||
};
|
};
|
||||||
|
|
||||||
const STRINGS_EN: Strings = Strings {
|
const STRINGS_EN: Strings = Strings {
|
||||||
@@ -64,6 +66,7 @@ const STRINGS_EN: Strings = Strings {
|
|||||||
confirm_no: "Cancel",
|
confirm_no: "Cancel",
|
||||||
faillock_attempts_remaining: "{n} attempt(s) remaining before lockout!",
|
faillock_attempts_remaining: "{n} attempt(s) remaining before lockout!",
|
||||||
faillock_locked: "Account may be locked",
|
faillock_locked: "Account may be locked",
|
||||||
|
auth_timeout: "Authentication timed out — please try again",
|
||||||
};
|
};
|
||||||
|
|
||||||
fn parse_lang_prefix(lang: &str) -> String {
|
fn parse_lang_prefix(lang: &str) -> String {
|
||||||
@@ -97,10 +100,13 @@ pub fn load_strings(locale: Option<&str>) -> &'static Strings {
|
|||||||
match locale { "de" => &STRINGS_DE, _ => &STRINGS_EN }
|
match locale { "de" => &STRINGS_DE, _ => &STRINGS_EN }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns a warning when the user is close to lockout (2 or fewer attempts remaining).
|
||||||
|
/// Caller is responsible for handling the locked state (count >= max_attempts).
|
||||||
pub fn faillock_warning(attempt_count: u32, max_attempts: u32, strings: &Strings) -> Option<String> {
|
pub fn faillock_warning(attempt_count: u32, max_attempts: u32, strings: &Strings) -> Option<String> {
|
||||||
if attempt_count >= max_attempts { return Some(strings.faillock_locked.to_string()); }
|
let remaining = max_attempts.saturating_sub(attempt_count);
|
||||||
let remaining = max_attempts - attempt_count;
|
if remaining > 0 && remaining <= 2 {
|
||||||
if remaining == 1 { return Some(strings.faillock_attempts_remaining.replace("{n}", &remaining.to_string())); }
|
return Some(strings.faillock_attempts_remaining.replace("{n}", &remaining.to_string()));
|
||||||
|
}
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,7 +140,35 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test] fn faillock_zero() { assert!(faillock_warning(0, 3, load_strings(Some("en"))).is_none()); }
|
#[test] fn faillock_zero() { assert!(faillock_warning(0, 3, load_strings(Some("en"))).is_none()); }
|
||||||
#[test] fn faillock_one() { assert!(faillock_warning(1, 3, load_strings(Some("en"))).is_none()); }
|
#[test] fn faillock_one() { assert!(faillock_warning(1, 3, load_strings(Some("en"))).is_some()); }
|
||||||
#[test] fn faillock_two() { assert!(faillock_warning(2, 3, load_strings(Some("en"))).is_some()); }
|
#[test] fn faillock_two() { assert!(faillock_warning(2, 3, load_strings(Some("en"))).is_some()); }
|
||||||
#[test] fn faillock_three() { assert_eq!(faillock_warning(3, 3, load_strings(Some("en"))).unwrap(), "Account may be locked"); }
|
#[test] fn faillock_three() { assert!(faillock_warning(3, 3, load_strings(Some("en"))).is_none()); }
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn faillock_caller_contract() {
|
||||||
|
// Mirrors the lockscreen.rs usage: caller handles count >= max separately,
|
||||||
|
// faillock_warning is only called when count < max.
|
||||||
|
let max = 3u32;
|
||||||
|
let strings = load_strings(Some("en"));
|
||||||
|
for count in 0..max {
|
||||||
|
let result = faillock_warning(count, max, strings);
|
||||||
|
let remaining = max - count;
|
||||||
|
if remaining <= 2 {
|
||||||
|
assert!(result.is_some(), "should warn at count={count} (remaining={remaining})");
|
||||||
|
} else {
|
||||||
|
assert!(result.is_none(), "should not warn at count={count}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn faillock_warns_progressively_with_higher_max() {
|
||||||
|
let strings = load_strings(Some("en"));
|
||||||
|
// With max=5: warn at count 3 (rem=2) and count 4 (rem=1), not at 0-2
|
||||||
|
assert!(faillock_warning(0, 5, strings).is_none());
|
||||||
|
assert!(faillock_warning(2, 5, strings).is_none());
|
||||||
|
assert!(faillock_warning(3, 5, strings).is_some());
|
||||||
|
assert!(faillock_warning(4, 5, strings).is_some());
|
||||||
|
assert!(faillock_warning(5, 5, strings).is_none()); // at max, caller handles lockout
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+153
-30
@@ -7,7 +7,7 @@ use glib::clone;
|
|||||||
use graphene_rs as graphene;
|
use graphene_rs as graphene;
|
||||||
use gtk4::prelude::*;
|
use gtk4::prelude::*;
|
||||||
use gtk4::{self as gtk, gio};
|
use gtk4::{self as gtk, gio};
|
||||||
use std::cell::RefCell;
|
use std::cell::{Cell, RefCell};
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
@@ -32,6 +32,7 @@ pub struct LockscreenHandles {
|
|||||||
|
|
||||||
const AVATAR_SIZE: i32 = 128;
|
const AVATAR_SIZE: i32 = 128;
|
||||||
const FAILLOCK_MAX_ATTEMPTS: u32 = 3;
|
const FAILLOCK_MAX_ATTEMPTS: u32 = 3;
|
||||||
|
const PAM_TIMEOUT_SECS: u64 = 30;
|
||||||
|
|
||||||
/// Shared mutable state for the lockscreen.
|
/// Shared mutable state for the lockscreen.
|
||||||
struct LockscreenState {
|
struct LockscreenState {
|
||||||
@@ -44,7 +45,7 @@ struct LockscreenState {
|
|||||||
/// The `blur_cache` and `avatar_cache` are shared across monitors for multi-monitor
|
/// The `blur_cache` and `avatar_cache` are shared across monitors for multi-monitor
|
||||||
/// setups, avoiding redundant GPU renders and SVG rasterizations.
|
/// setups, avoiding redundant GPU renders and SVG rasterizations.
|
||||||
pub fn create_lockscreen_window(
|
pub fn create_lockscreen_window(
|
||||||
bg_texture: &gdk::Texture,
|
bg_texture: Option<&gdk::Texture>,
|
||||||
config: &Config,
|
config: &Config,
|
||||||
app: >k::Application,
|
app: >k::Application,
|
||||||
unlock_callback: Rc<dyn Fn()>,
|
unlock_callback: Rc<dyn Fn()>,
|
||||||
@@ -86,9 +87,11 @@ pub fn create_lockscreen_window(
|
|||||||
let overlay = gtk::Overlay::new();
|
let overlay = gtk::Overlay::new();
|
||||||
window.set_child(Some(&overlay));
|
window.set_child(Some(&overlay));
|
||||||
|
|
||||||
// Background wallpaper
|
// Background wallpaper (if available — otherwise GTK background color shows through)
|
||||||
let background = create_background_picture(bg_texture, config.background_blur, blur_cache);
|
if let Some(texture) = bg_texture {
|
||||||
overlay.set_child(Some(&background));
|
let background = create_background_picture(texture, config.background_blur, blur_cache);
|
||||||
|
overlay.set_child(Some(&background));
|
||||||
|
}
|
||||||
|
|
||||||
// Centered vertical box
|
// Centered vertical box
|
||||||
let main_box = gtk::Box::new(gtk::Orientation::Vertical, 0);
|
let main_box = gtk::Box::new(gtk::Orientation::Vertical, 0);
|
||||||
@@ -219,13 +222,19 @@ pub fn create_lockscreen_window(
|
|||||||
|
|
||||||
overlay.add_overlay(&power_box);
|
overlay.add_overlay(&power_box);
|
||||||
|
|
||||||
// Password entry "activate" handler
|
// Password entry "activate" handler.
|
||||||
|
// A generation counter tracks which auth attempt is current. When the user
|
||||||
|
// submits a new password, the generation increments — stale PAM results from
|
||||||
|
// prior attempts are ignored (except success: a correct password always unlocks).
|
||||||
let username = user.username.clone();
|
let username = user.username.clone();
|
||||||
|
let auth_generation = Rc::new(Cell::new(0u32));
|
||||||
password_entry.connect_activate(clone!(
|
password_entry.connect_activate(clone!(
|
||||||
#[strong]
|
#[strong]
|
||||||
state,
|
state,
|
||||||
#[strong]
|
#[strong]
|
||||||
unlock_callback,
|
unlock_callback,
|
||||||
|
#[strong]
|
||||||
|
auth_generation,
|
||||||
#[weak]
|
#[weak]
|
||||||
error_label,
|
error_label,
|
||||||
#[weak]
|
#[weak]
|
||||||
@@ -240,6 +249,35 @@ pub fn create_lockscreen_window(
|
|||||||
let username = username.clone();
|
let username = username.clone();
|
||||||
let unlock_cb = unlock_callback.clone();
|
let unlock_cb = unlock_callback.clone();
|
||||||
|
|
||||||
|
// Invalidate stale timeouts/results from prior attempts
|
||||||
|
let auth_gen = auth_generation.get().wrapping_add(1);
|
||||||
|
auth_generation.set(auth_gen);
|
||||||
|
let gen_timeout = auth_generation.clone();
|
||||||
|
let gen_result = auth_generation.clone();
|
||||||
|
|
||||||
|
// If PAM hangs (e.g. broken LDAP module), the timeout re-enables the UI
|
||||||
|
glib::timeout_add_local_once(
|
||||||
|
std::time::Duration::from_secs(PAM_TIMEOUT_SECS),
|
||||||
|
clone!(
|
||||||
|
#[weak]
|
||||||
|
error_label,
|
||||||
|
#[weak]
|
||||||
|
password_entry,
|
||||||
|
move || {
|
||||||
|
if gen_timeout.get() != auth_gen {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
log::error!("PAM authentication timed out after {PAM_TIMEOUT_SECS}s");
|
||||||
|
let strings = load_strings(None);
|
||||||
|
password_entry.set_text("");
|
||||||
|
password_entry.set_sensitive(true);
|
||||||
|
password_entry.grab_focus();
|
||||||
|
error_label.set_text(strings.auth_timeout);
|
||||||
|
error_label.set_visible(true);
|
||||||
|
}
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
glib::spawn_future_local(clone!(
|
glib::spawn_future_local(clone!(
|
||||||
#[strong]
|
#[strong]
|
||||||
state,
|
state,
|
||||||
@@ -253,6 +291,20 @@ pub fn create_lockscreen_window(
|
|||||||
auth::authenticate(&user, &password)
|
auth::authenticate(&user, &password)
|
||||||
}).await;
|
}).await;
|
||||||
|
|
||||||
|
// Stale result from a superseded attempt — only unlock on success
|
||||||
|
// (a correct password should always unlock, regardless of timing)
|
||||||
|
if gen_result.get() != auth_gen {
|
||||||
|
if matches!(result, Ok(true)) {
|
||||||
|
let s = state.borrow();
|
||||||
|
if let Some(ref fp_rc) = s.fp_listener_rc {
|
||||||
|
fp_rc.borrow_mut().stop();
|
||||||
|
}
|
||||||
|
drop(s);
|
||||||
|
unlock_cb();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
match result {
|
match result {
|
||||||
Ok(true) => {
|
Ok(true) => {
|
||||||
let s = state.borrow();
|
let s = state.borrow();
|
||||||
@@ -371,10 +423,12 @@ pub fn start_fingerprint(
|
|||||||
let unlock_cb_fp = handles.unlock_callback.clone();
|
let unlock_cb_fp = handles.unlock_callback.clone();
|
||||||
|
|
||||||
let fp_rc_success = fp_rc.clone();
|
let fp_rc_success = fp_rc.clone();
|
||||||
|
let fp_username = handles.username.clone();
|
||||||
let on_success = move || {
|
let on_success = move || {
|
||||||
let label = fp_label_success.clone();
|
let label = fp_label_success.clone();
|
||||||
let cb = unlock_cb_fp.clone();
|
let cb = unlock_cb_fp.clone();
|
||||||
let fp = fp_rc_success.clone();
|
let fp = fp_rc_success.clone();
|
||||||
|
let username = fp_username.clone();
|
||||||
glib::idle_add_local_once(move || {
|
glib::idle_add_local_once(move || {
|
||||||
let strings = load_strings(None);
|
let strings = load_strings(None);
|
||||||
label.set_text(strings.fingerprint_success);
|
label.set_text(strings.fingerprint_success);
|
||||||
@@ -382,7 +436,39 @@ pub fn start_fingerprint(
|
|||||||
// stop() is idempotent — cleanup_dbus() already ran inside on_verify_status,
|
// stop() is idempotent — cleanup_dbus() already ran inside on_verify_status,
|
||||||
// but this mirrors the PAM success path for defense-in-depth.
|
// but this mirrors the PAM success path for defense-in-depth.
|
||||||
fp.borrow_mut().stop();
|
fp.borrow_mut().stop();
|
||||||
cb();
|
|
||||||
|
// Enforce PAM account policies (lockout, expiry) before unlocking.
|
||||||
|
// Fingerprint auth bypasses pam_authenticate, so we must explicitly
|
||||||
|
// check account restrictions via pam_acct_mgmt.
|
||||||
|
glib::spawn_future_local(async move {
|
||||||
|
let user = username.clone();
|
||||||
|
let result = gio::spawn_blocking(move || {
|
||||||
|
auth::check_account(&user)
|
||||||
|
}).await;
|
||||||
|
match result {
|
||||||
|
Ok(true) => cb(),
|
||||||
|
_ => {
|
||||||
|
log::error!("PAM account check failed after fingerprint auth");
|
||||||
|
let strings = load_strings(None);
|
||||||
|
label.set_text(strings.wrong_password);
|
||||||
|
label.remove_css_class("success");
|
||||||
|
label.add_css_class("failed");
|
||||||
|
// Restart FP verification after delay — the failure may be
|
||||||
|
// transient (e.g. PAM module timeout). If the account is truly
|
||||||
|
// locked, check_account will fail again on next match.
|
||||||
|
glib::timeout_add_local_once(
|
||||||
|
std::time::Duration::from_secs(2),
|
||||||
|
move || {
|
||||||
|
label.set_text(load_strings(None).fingerprint_prompt);
|
||||||
|
label.remove_css_class("failed");
|
||||||
|
glib::spawn_future_local(async move {
|
||||||
|
FingerprintListener::resume_async(&fp, &username).await;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -430,18 +516,16 @@ pub fn start_fingerprint(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Load the wallpaper as a texture once, for sharing across all windows.
|
/// Load the wallpaper as a texture once, for sharing across all windows.
|
||||||
|
/// Returns None if no wallpaper path is provided or the file cannot be loaded.
|
||||||
/// Blur is applied at render time via GPU (GskBlurNode), not here.
|
/// Blur is applied at render time via GPU (GskBlurNode), not here.
|
||||||
pub fn load_background_texture(bg_path: &Path) -> gdk::Texture {
|
pub fn load_background_texture(bg_path: &Path) -> Option<gdk::Texture> {
|
||||||
let fallback = "/dev/moonarch/moonlock/wallpaper.jpg";
|
let file = gio::File::for_path(bg_path);
|
||||||
|
match gdk::Texture::from_file(&file) {
|
||||||
if bg_path.starts_with("/dev/moonarch/moonlock") {
|
Ok(texture) => Some(texture),
|
||||||
let resource_path = bg_path.to_str().unwrap_or(fallback);
|
Err(e) => {
|
||||||
gdk::Texture::from_resource(resource_path)
|
log::warn!("Failed to load wallpaper {}: {e}", bg_path.display());
|
||||||
} else {
|
None
|
||||||
let file = gio::File::for_path(bg_path);
|
}
|
||||||
gdk::Texture::from_file(&file).unwrap_or_else(|_| {
|
|
||||||
gdk::Texture::from_resource(fallback)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -481,8 +565,20 @@ fn create_background_picture(
|
|||||||
background
|
background
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Maximum texture dimension for blur input. Textures larger than this are
|
||||||
|
/// downscaled before blurring — the blur destroys detail anyway, so there is
|
||||||
|
/// no visible quality loss, but GPU work is reduced significantly.
|
||||||
|
const MAX_BLUR_DIMENSION: f32 = 1920.0;
|
||||||
|
|
||||||
/// Render a blurred texture using the widget's GPU renderer.
|
/// Render a blurred texture using the widget's GPU renderer.
|
||||||
/// Returns None if the renderer is not available.
|
/// Returns None if the renderer is not available.
|
||||||
|
///
|
||||||
|
/// To avoid edge darkening (blur samples transparent pixels outside bounds),
|
||||||
|
/// the texture is rendered with padding equal to 3x the blur sigma. The blur
|
||||||
|
/// is applied to the padded area, then cropped back to the original size.
|
||||||
|
///
|
||||||
|
/// Large textures (> MAX_BLUR_DIMENSION) are downscaled before blurring to
|
||||||
|
/// reduce GPU work. The sigma is scaled proportionally.
|
||||||
fn render_blurred_texture(
|
fn render_blurred_texture(
|
||||||
widget: &impl IsA<gtk::Widget>,
|
widget: &impl IsA<gtk::Widget>,
|
||||||
texture: &gdk::Texture,
|
texture: &gdk::Texture,
|
||||||
@@ -490,18 +586,36 @@ fn render_blurred_texture(
|
|||||||
) -> Option<gdk::Texture> {
|
) -> Option<gdk::Texture> {
|
||||||
let native = widget.native()?;
|
let native = widget.native()?;
|
||||||
let renderer = native.renderer()?;
|
let renderer = native.renderer()?;
|
||||||
|
|
||||||
|
let orig_w = texture.width() as f32;
|
||||||
|
let orig_h = texture.height() as f32;
|
||||||
|
|
||||||
|
// Downscale large textures to reduce GPU blur work
|
||||||
|
let max_dim = orig_w.max(orig_h);
|
||||||
|
let scale = if max_dim > MAX_BLUR_DIMENSION {
|
||||||
|
MAX_BLUR_DIMENSION / max_dim
|
||||||
|
} else {
|
||||||
|
1.0
|
||||||
|
};
|
||||||
|
let w = (orig_w * scale).round();
|
||||||
|
let h = (orig_h * scale).round();
|
||||||
|
let scaled_sigma = sigma * scale;
|
||||||
|
|
||||||
|
// Padding must cover the blur kernel radius (typically ~3x sigma)
|
||||||
|
let pad = (scaled_sigma * 3.0).ceil();
|
||||||
|
|
||||||
let snapshot = gtk::Snapshot::new();
|
let snapshot = gtk::Snapshot::new();
|
||||||
let bounds = graphene::Rect::new(
|
// Clip output to scaled texture size
|
||||||
0.0,
|
snapshot.push_clip(&graphene::Rect::new(pad, pad, w, h));
|
||||||
0.0,
|
snapshot.push_blur(scaled_sigma as f64);
|
||||||
texture.width() as f32,
|
// Render texture with padding on all sides (edges repeat via oversized bounds)
|
||||||
texture.height() as f32,
|
snapshot.append_texture(texture, &graphene::Rect::new(-pad, -pad, w + 2.0 * pad, h + 2.0 * pad));
|
||||||
);
|
snapshot.pop(); // blur
|
||||||
snapshot.push_blur(sigma as f64);
|
snapshot.pop(); // clip
|
||||||
snapshot.append_texture(texture, &bounds);
|
|
||||||
snapshot.pop();
|
|
||||||
let node = snapshot.to_node()?;
|
let node = snapshot.to_node()?;
|
||||||
Some(renderer.render_texture(&node, None))
|
let viewport = graphene::Rect::new(pad, pad, w, h);
|
||||||
|
Some(renderer.render_texture(&node, Some(&viewport)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Load an image file and set it as the avatar. Stores the texture in the cache.
|
/// Load an image file and set it as the avatar. Stores the texture in the cache.
|
||||||
@@ -510,13 +624,22 @@ fn set_avatar_from_file(
|
|||||||
path: &Path,
|
path: &Path,
|
||||||
cache: &Rc<RefCell<Option<gdk::Texture>>>,
|
cache: &Rc<RefCell<Option<gdk::Texture>>>,
|
||||||
) {
|
) {
|
||||||
match Pixbuf::from_file_at_scale(path.to_str().unwrap_or(""), AVATAR_SIZE, AVATAR_SIZE, true) {
|
let path_str = match path.to_str() {
|
||||||
|
Some(s) => s,
|
||||||
|
None => {
|
||||||
|
log::warn!("Avatar path is not valid UTF-8: {:?}", path);
|
||||||
|
image.set_icon_name(Some("avatar-default-symbolic"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match Pixbuf::from_file_at_scale(path_str, AVATAR_SIZE, AVATAR_SIZE, true) {
|
||||||
Ok(pixbuf) => {
|
Ok(pixbuf) => {
|
||||||
let texture = gdk::Texture::for_pixbuf(&pixbuf);
|
let texture = gdk::Texture::for_pixbuf(&pixbuf);
|
||||||
image.set_paintable(Some(&texture));
|
image.set_paintable(Some(&texture));
|
||||||
*cache.borrow_mut() = Some(texture);
|
*cache.borrow_mut() = Some(texture);
|
||||||
}
|
}
|
||||||
Err(_) => {
|
Err(e) => {
|
||||||
|
log::warn!("Failed to load avatar from {:?}: {e}", path);
|
||||||
image.set_icon_name(Some("avatar-default-symbolic"));
|
image.set_icon_name(Some("avatar-default-symbolic"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-10
@@ -24,7 +24,7 @@ fn load_css(display: &gdk::Display) {
|
|||||||
gtk::style_context_add_provider_for_display(
|
gtk::style_context_add_provider_for_display(
|
||||||
display,
|
display,
|
||||||
&css_provider,
|
&css_provider,
|
||||||
gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,
|
gtk::STYLE_PROVIDER_PRIORITY_USER,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,16 +40,14 @@ fn activate(app: >k::Application) {
|
|||||||
load_css(&display);
|
load_css(&display);
|
||||||
|
|
||||||
let config = config::load_config(None);
|
let config = config::load_config(None);
|
||||||
let bg_path = config::resolve_background_path(&config);
|
|
||||||
let bg_texture = lockscreen::load_background_texture(&bg_path);
|
|
||||||
|
|
||||||
if gtk4_session_lock::is_supported() {
|
if gtk4_session_lock::is_supported() {
|
||||||
activate_with_session_lock(app, &display, &bg_texture, &config);
|
activate_with_session_lock(app, &display, &config);
|
||||||
} else {
|
} else {
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
{
|
{
|
||||||
log::warn!("ext-session-lock-v1 not supported — running in development mode");
|
log::warn!("ext-session-lock-v1 not supported — running in development mode");
|
||||||
activate_without_lock(app, &bg_texture, &config);
|
activate_without_lock(app, &config);
|
||||||
}
|
}
|
||||||
#[cfg(not(debug_assertions))]
|
#[cfg(not(debug_assertions))]
|
||||||
{
|
{
|
||||||
@@ -62,12 +60,15 @@ fn activate(app: >k::Application) {
|
|||||||
fn activate_with_session_lock(
|
fn activate_with_session_lock(
|
||||||
app: >k::Application,
|
app: >k::Application,
|
||||||
display: &gdk::Display,
|
display: &gdk::Display,
|
||||||
bg_texture: &gdk::Texture,
|
|
||||||
config: &config::Config,
|
config: &config::Config,
|
||||||
) {
|
) {
|
||||||
let lock = gtk4_session_lock::Instance::new();
|
let lock = gtk4_session_lock::Instance::new();
|
||||||
lock.lock();
|
lock.lock();
|
||||||
|
|
||||||
|
// Load wallpaper AFTER lock — disk I/O must not delay the lock acquisition
|
||||||
|
let bg_texture = config::resolve_background_path(config)
|
||||||
|
.and_then(|path| lockscreen::load_background_texture(&path));
|
||||||
|
|
||||||
let monitors = display.monitors();
|
let monitors = display.monitors();
|
||||||
|
|
||||||
// Shared unlock callback — unlocks session and quits.
|
// Shared unlock callback — unlocks session and quits.
|
||||||
@@ -99,7 +100,7 @@ fn activate_with_session_lock(
|
|||||||
.and_then(|obj| obj.downcast::<gdk::Monitor>().ok())
|
.and_then(|obj| obj.downcast::<gdk::Monitor>().ok())
|
||||||
{
|
{
|
||||||
let handles = lockscreen::create_lockscreen_window(
|
let handles = lockscreen::create_lockscreen_window(
|
||||||
bg_texture,
|
bg_texture.as_ref(),
|
||||||
config,
|
config,
|
||||||
app,
|
app,
|
||||||
unlock_callback.clone(),
|
unlock_callback.clone(),
|
||||||
@@ -115,7 +116,7 @@ fn activate_with_session_lock(
|
|||||||
|
|
||||||
if !created_any {
|
if !created_any {
|
||||||
log::error!("No lockscreen windows created — screen stays locked (compositor policy)");
|
log::error!("No lockscreen windows created — screen stays locked (compositor policy)");
|
||||||
return;
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Async fprintd initialization — runs after windows are visible
|
// Async fprintd initialization — runs after windows are visible
|
||||||
@@ -158,9 +159,11 @@ fn init_fingerprint_async(all_handles: Vec<lockscreen::LockscreenHandles>) {
|
|||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
fn activate_without_lock(
|
fn activate_without_lock(
|
||||||
app: >k::Application,
|
app: >k::Application,
|
||||||
bg_texture: &gdk::Texture,
|
|
||||||
config: &config::Config,
|
config: &config::Config,
|
||||||
) {
|
) {
|
||||||
|
let bg_texture = config::resolve_background_path(config)
|
||||||
|
.and_then(|path| lockscreen::load_background_texture(&path));
|
||||||
|
|
||||||
let app_clone = app.clone();
|
let app_clone = app.clone();
|
||||||
let unlock_callback: Rc<dyn Fn()> = Rc::new(move || {
|
let unlock_callback: Rc<dyn Fn()> = Rc::new(move || {
|
||||||
app_clone.quit();
|
app_clone.quit();
|
||||||
@@ -169,7 +172,7 @@ fn activate_without_lock(
|
|||||||
let blur_cache = Rc::new(RefCell::new(None));
|
let blur_cache = Rc::new(RefCell::new(None));
|
||||||
let avatar_cache = Rc::new(RefCell::new(None));
|
let avatar_cache = Rc::new(RefCell::new(None));
|
||||||
let handles = lockscreen::create_lockscreen_window(
|
let handles = lockscreen::create_lockscreen_window(
|
||||||
bg_texture,
|
bg_texture.as_ref(),
|
||||||
config,
|
config,
|
||||||
app,
|
app,
|
||||||
unlock_callback,
|
unlock_callback,
|
||||||
|
|||||||
+14
-4
@@ -18,7 +18,13 @@ pub struct User {
|
|||||||
pub fn get_current_user() -> Option<User> {
|
pub fn get_current_user() -> Option<User> {
|
||||||
let uid = getuid();
|
let uid = getuid();
|
||||||
let nix_user = NixUser::from_uid(uid).ok()??;
|
let nix_user = NixUser::from_uid(uid).ok()??;
|
||||||
let gecos = nix_user.gecos.to_str().unwrap_or("").to_string();
|
let gecos = match nix_user.gecos.to_str() {
|
||||||
|
Ok(s) => s.to_string(),
|
||||||
|
Err(_) => {
|
||||||
|
log::warn!("GECOS field is not valid UTF-8, falling back to username");
|
||||||
|
String::new()
|
||||||
|
}
|
||||||
|
};
|
||||||
let display_name = if !gecos.is_empty() {
|
let display_name = if !gecos.is_empty() {
|
||||||
let first = gecos.split(',').next().unwrap_or("");
|
let first = gecos.split(',').next().unwrap_or("");
|
||||||
if first.is_empty() { nix_user.name.clone() } else { first.to_string() }
|
if first.is_empty() { nix_user.name.clone() } else { first.to_string() }
|
||||||
@@ -31,13 +37,17 @@ pub fn get_avatar_path(home: &Path, username: &str) -> Option<PathBuf> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_avatar_path_with(home: &Path, username: &str, accountsservice_dir: &Path) -> Option<PathBuf> {
|
pub fn get_avatar_path_with(home: &Path, username: &str, accountsservice_dir: &Path) -> Option<PathBuf> {
|
||||||
// ~/.face takes priority
|
// ~/.face takes priority — single stat via symlink_metadata to avoid TOCTOU
|
||||||
let face = home.join(".face");
|
let face = home.join(".face");
|
||||||
if face.exists() && !face.is_symlink() { return Some(face); }
|
if let Ok(meta) = face.symlink_metadata() {
|
||||||
|
if meta.is_file() && !meta.file_type().is_symlink() { return Some(face); }
|
||||||
|
}
|
||||||
// AccountsService icon
|
// AccountsService icon
|
||||||
if accountsservice_dir.exists() {
|
if accountsservice_dir.exists() {
|
||||||
let icon = accountsservice_dir.join(username);
|
let icon = accountsservice_dir.join(username);
|
||||||
if icon.exists() && !icon.is_symlink() { return Some(icon); }
|
if let Ok(meta) = icon.symlink_metadata() {
|
||||||
|
if meta.is_file() && !meta.file_type().is_symlink() { return Some(icon); }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user