Lock: add session lock from power button and chandra-ctl lock
CI / test (push) Failing after 52s

- Lock the session from the power button or `chandra-ctl lock`
- Unlock with a face or the password; the password always works
- Add compositor lock module with tests, and a polkit unlock policy (org.chandra.unlock)
- Document the lock flow in docs/lock.md and link it from the README
- Add generated interface bindings for the compositor and widget components
This commit is contained in:
nandi committed 2026-11-29 03:24:46 -08:00
1 parent 7501fc3ad9
commit c790f96e58
131 files changed
+4693 -274

No files matched your search

+109
View File
@@ -277,6 +277,115 @@ pub fn PolkitAgent::registered(self : PolkitAgent) -> Bool {
self.registered
}
///| Parse an unsigned 64-bit decimal integer (returns None if empty, >20 chars, or non-digit).
fn parse_u64(s : String) -> UInt64? {
if s.length() == 0 || s.length() > 20 {
return None
}
let mut v = 0UL
for c in s {
if c < '0' || c > '9' {
return None
}
v = v * 10UL + (c.to_int() - '0'.to_int()).to_uint64()
}
Some(v)
}
///| Build a polkit `unix-process` subject from `/proc/<pid>/stat` and `/proc/<pid>/status` text.
pub fn process_subject_for(pid : Int, stat : String, status : String) -> @network.DValue {
let start_time = match stat.rev_find(")") {
Some(i) => {
let parts = stat[i + 1:].to_string().trim(chars=" \t\n").to_string().split(" ").map(v => v.to_string()).filter(v => v != "").to_array()
if parts.length() > 19 {
parse_u64(parts[19]).unwrap_or(0UL)
} else {
0UL
}
}
None => 0UL
}
let uid = uid_from_status(status)
Struct([
Str("unix-process"),
@network.dict("v", [
("pid", Variant(U32(pid.reinterpret_as_uint()))),
("start-time", Variant(U64(start_time))),
("uid", Variant(I32(uid))),
]),
])
}
///| The polkit subject representing the current agent process (`unix-process`).
fn process_subject() -> @network.DValue {
let pid = @sys.getpid()
let stat = @utf8.decode_lossy(@sys.read_proc_bytes("/proc/" + pid.to_string() + "/stat"))
let status = @utf8.decode_lossy(@sys.read_proc_bytes("/proc/" + pid.to_string() + "/status"))
process_subject_for(pid, stat, status)
}
///| Ask polkit to authorize `action_id` for the agent process, allowing user interaction: polkit
/// then drives this same agent's dialog (face via PAM, then password), and the reply says whether
/// it succeeded. Used for session unlock (org.chandra.unlock). False before registration or without a bus.
pub fn PolkitAgent::check_unlock(
self : PolkitAgent,
action_id : String,
cancel_id : String,
on_result : (Bool) -> Unit,
) -> Bool {
if !self.registered {
return false
}
match self.bus {
Some(bus) => {
let serial = bus.call(
@network.DMessage::call(authority_name, authority_path, authority_iface, "CheckAuthorization", [
process_subject(),
Str(action_id),
@network.dict("s", []),
U32(1U), // AllowUserInteraction
Str(cancel_id),
]),
on_reply=fn(m) {
let ok = match m {
{ mtype: 2, body: [Struct([Bool(a), ..]), ..], .. } => a
{ mtype: 2, .. } => {
alog("unlock: unexpected CheckAuthorization reply")
false
}
_ => {
alog("unlock: CheckAuthorization error: " + m.error_text())
false
}
}
on_result(ok)
},
)
serial != 0
}
None => false
}
}
///| Cancel an in-flight CheckAuthorization call identified by `cancel_id`.
pub fn PolkitAgent::cancel_unlock(self : PolkitAgent, cancel_id : String) -> Unit {
if cancel_id == "" {
return
}
match self.bus {
Some(bus) =>
ignore(
bus.call(
@network.DMessage::call(authority_name, authority_path, authority_iface, "CancelCheckAuthorization", [
Str(cancel_id),
]),
on_reply=fn(_) { () },
),
)
None => ()
}
}
///| Why the last start failed ("" when it didn't).
pub fn PolkitAgent::error(self : PolkitAgent) -> String {
self.error
+80
View File
@@ -28,6 +28,12 @@ pub struct AgentLoop {
mut id : String
mut next_id : Int
mut was_registered : Bool
/// An unlock authorization (org.chandra.unlock) is out to polkit; ignore further `unlock`s.
mut unlocking : Bool
/// Cancellation id passed to polkit's CheckAuthorization / CancelCheckAuthorization.
mut unlock_cancel_id : String
/// Monotonic counter so stale CheckAuthorization replies after cancel are ignored.
mut unlock_seq : Int
/// Done: the main loop exits.
mut finished : Bool
}
@@ -56,6 +62,9 @@ pub fn AgentLoop::new(
id: "",
next_id: 1,
was_registered: false,
unlocking: false,
unlock_cancel_id: "",
unlock_seq: 0,
finished: false,
}
}
@@ -73,6 +82,9 @@ pub fn AgentLoop::new_demo(link_fd : Int, mode : String) -> AgentLoop {
id: "",
next_id: 1,
was_registered: false,
unlocking: false,
unlock_cancel_id: "",
unlock_seq: 0,
finished: false,
}
}
@@ -160,10 +172,78 @@ fn AgentLoop::close_request(self : AgentLoop, result : Result[Unit, String]?) ->
}
}
///| Unlock the session: ask polkit to authorize org.chandra.unlock. polkit drives this agent's
/// dialog (face via the polkit-1 PAM stack, then password); the reply tells the compositor
/// `unlocked` or `unlock-failed`. Without polkit (demo) there is nothing to check.
fn AgentLoop::begin_unlock(self : AgentLoop) -> Unit {
match self.polkit {
Some(p) => {
if self.unlocking {
return
}
self.unlock_seq = self.unlock_seq + 1
let seq = self.unlock_seq
let cid = "chandra-unlock-" + seq.to_string()
self.unlocking = true
self.unlock_cancel_id = cid
let started = p.check_unlock("org.chandra.unlock", cid, fn(ok) {
if self.unlock_seq != seq {
return
}
self.unlocking = false
self.unlock_cancel_id = ""
ignore(self.link.send([if ok { "unlocked" } else { "unlock-failed" }]))
})
if !started {
self.unlocking = false
self.unlock_cancel_id = ""
alog("unlock: polkit is not ready")
ignore(self.link.send(["unlock-failed"]))
}
}
None => ignore(self.link.send(["unlock-failed"]))
}
}
///| Cancel an in-flight unlock authorization (e.g., screen blanked again before completion).
fn AgentLoop::cancel_unlock(self : AgentLoop) -> Unit {
if !self.unlocking {
return
}
let cid = self.unlock_cancel_id
self.unlock_seq = self.unlock_seq + 1
self.unlocking = false
self.unlock_cancel_id = ""
match self.machine {
Some(m) if m.req.action_id == "org.chandra.unlock" =>
self.close_request(Some(Err("The unlock request was cancelled")))
_ => ()
}
match self.polkit {
Some(p) => p.cancel_unlock(cid)
None => ()
}
}
///| A message from the compositor.
fn AgentLoop::on_link(self : AgentLoop, line : FixedArray[Byte]) -> Unit {
let f = split_fields(line)
zero(line)
// Session unlock (lock.mbt) is a one-field message, independent of any request/dialog id.
if f.length() >= 1 && field_text(f[0]) == "unlock" {
for b in f {
zero(b)
}
self.begin_unlock()
return
}
if f.length() >= 1 && field_text(f[0]) == "cancel-unlock" {
for b in f {
zero(b)
}
self.cancel_unlock()
return
}
if f.length() < 2 {
return
}
+11
View File
@@ -234,6 +234,17 @@ pub fn describe(req : AuthRequest, cmdline? : (Int) -> Array[String] = proc_cmdl
details,
}
}
// Session unlock: clear lock-screen wording instead of the generic system-action fallback.
if req.action_id == "org.chandra.unlock" {
add("Action", req.action_id)
return {
title: "Screen locked",
subtitle: "Look at the camera or enter your password to unlock.",
command: "",
program: "",
details,
}
}
// Anything else: polkit's message is the best we have.
add("Requested by", who(if subject > 0 { subject } else { caller }))
add("Unit", req.detail("unit"))
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC
"-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
"http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
<!--
Session unlock for Chandra (docs/lock.md). The compositor locks the session (power button,
or `chandra-ctl lock`) and asks its polkit agent to authorize this action to unlock. Because
it is auth_self (never _keep), polkit prompts every time, and the polkit-1 PAM stack runs the
camera first (pam_chandra_face.so) with the password as the fallback.
-->
<policyconfig>
<vendor>Chandra</vendor>
<action id="org.chandra.unlock">
<description>Unlock the session</description>
<message>Authenticate to unlock the screen</message>
<defaults>
<allow_any>auth_self</allow_any>
<allow_inactive>auth_self</allow_inactive>
<allow_active>auth_self</allow_active>
</defaults>
</action>
</policyconfig>
+35
View File
@@ -594,3 +594,38 @@ test "face unlock: Chandra's and Howdy's PAM messages" {
assert_eq(@polkit.face_message("Place your finger on the fingerprint reader", false), None)
assert_eq(@polkit.face_message("The account is locked due to 3 failed logins.", true), None)
}
///|
test "process_subject_for parses /proc/<pid>/stat with spaces/parens and /proc/<pid>/status Uid" {
let stat = "4210 (chandra (polkit) agent) S 1 4210 4210 0 -1 4194304 100 0 0 0 1 0 0 0 20 0 1 0 987654321 12345 100"
let status = "Name:\tchandra-polkit\nState:\tS (sleeping)\nUid:\t1000\t1000\t1000\t1000\nGid:\t1000\t1000\t1000\t1000\n"
let subj = @polkit.process_subject_for(4210, stat, status)
assert_eq(
subj,
@network.DValue::Struct([
Str("unix-process"),
@network.dict("v", [
("pid", Variant(U32(4210U))),
("start-time", Variant(U64(987654321UL))),
("uid", Variant(I32(1000))),
]),
]),
)
}
///|
test "describe: org.chandra.unlock uses clear lock-screen wording" {
let req : @polkit.AuthRequest = {
action_id: "org.chandra.unlock",
message: "Authenticate to unlock the screen",
icon_name: "",
details: {},
cookie: "c-unlock",
users: [{ uid: 1000, name: "nandi", real_name: "Nandi" }],
}
let desc = @polkit.describe(req, cmdline=_ => [], who=_ => "")
assert_eq(desc.title, "Screen locked")
assert_eq(desc.subtitle, "Look at the camera or enter your password to unlock.")
assert_eq(desc.command, "")
assert_eq(desc.details, [("Action", "org.chandra.unlock")])
}
+10 -5
View File
@@ -172,21 +172,26 @@ pub fn string_dict(v : @network.DValue) -> Map[String, String] {
out
}
///| Our uid, from /proc/self/status ("Uid:\treal\teffective..."); -1 when unknown.
pub fn own_uid() -> Int {
let text = @utf8.decode_lossy(@sys.read_proc_bytes("/proc/self/status"))
///| Parse real UID from `/proc/<pid>/status` ("Uid:\treal\teffective..."); -1 when unknown.
pub fn uid_from_status(text : String) -> Int {
for line in text.split("\n") {
let l = line.to_string()
if l.has_prefix("Uid:") {
let parts = l[4:].to_string().trim(chars=" \t").to_string().split("\t").to_array()
let rest = l[4:].to_string().replace_all(old="\t", new=" ")
let parts = rest.split(" ").map(v => v.to_string()).filter(v => v != "").to_array()
if parts.length() > 0 {
return parse_uint(parts[0].to_string().trim(chars=" ").to_string()).unwrap_or(-1)
return parse_uint(parts[0]).unwrap_or(-1)
}
}
}
-1
}
///| Our uid, from /proc/self/status ("Uid:\treal\teffective..."); -1 when unknown.
pub fn own_uid() -> Int {
uid_from_status(@utf8.decode_lossy(@sys.read_proc_bytes("/proc/self/status")))
}
///| The request BeginAuthentication's arguments describe (s s s a{ss} s a(sa{sv})); None when
/// they don't match. Users come from /etc/passwd and /etc/group.
pub fn AuthRequest::from_args(args : Array[@network.DValue]) -> AuthRequest? {