Files
chandra/compositor/polkit/agent_loop.mbt
T
nandi c790f96e58
CI / test (push) Failing after 52s
Lock: add session lock from power button and chandra-ctl lock
- 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
2026-11-29 03:24:46 -08:00

392 lines
11 KiB
MoonBit

///| chandra-polkit-agent's work (compositor/authagent is its main): be the session's polkit
/// agent and run each request's state machine, talking to the compositor over the link
/// (wire.mbt). In demo mode there is no polkit: one pretend request, then it exits.
///
/// Everything it logs goes to stderr, which is the session log; stdout is the link.
///| Log a line to stderr (the session log), never stdout (the link).
pub fn alog(msg : String) -> Unit {
eprintln("chandra-polkit-agent: " + msg)
}
///| `describe` with the real process lookups.
fn describe_default(r : AuthRequest) -> Description {
describe(r)
}
///| The agent's state.
pub struct AgentLoop {
link : LineConn
/// The polkit side; None in demo mode.
polkit : PolkitAgent?
/// Demo mode ("" for the real agent).
demo : String
start : Starter
describe : (AuthRequest) -> Description
/// The request being shown and its link id.
mut machine : AuthMachine?
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
}
///| The real agent on `link_fd`. `routes` reach polkit's helper (empty: the usual ones).
pub fn AgentLoop::new(
link_fd : Int,
polkit : PolkitAgent,
routes? : Array[HelperRoute] = [],
describer? : (AuthRequest) -> Description = describe_default,
) -> AgentLoop {
let start : Starter = fn(user, cookie) {
let rs = if routes.length() > 0 { routes } else { helper_routes() }
match HelperSession::start_any(rs, user, cookie) {
Ok(h) => Ok(h as &Conversation)
Err(e) => Err(e)
}
}
{
link: LineConn::new(link_fd),
polkit: Some(polkit),
demo: "",
start,
describe: describer,
machine: None,
id: "",
next_id: 1,
was_registered: false,
unlocking: false,
unlock_cancel_id: "",
unlock_seq: 0,
finished: false,
}
}
///| The demo agent on `link_fd`.
pub fn AgentLoop::new_demo(link_fd : Int, mode : String) -> AgentLoop {
let mode = if demo_modes.contains(mode) { mode } else { "password" }
{
link: LineConn::new(link_fd),
polkit: None,
demo: mode,
start: demo_starter(mode),
describe: describe_default,
machine: None,
id: "",
next_id: 1,
was_registered: false,
unlocking: false,
unlock_cancel_id: "",
unlock_seq: 0,
finished: false,
}
}
///| Begin: ask polkit to make us the session's agent (the answer comes in `step`), or open the
/// demo request. On failure the compositor is told why and the loop finishes.
pub fn AgentLoop::start(self : AgentLoop) -> Unit {
match self.polkit {
Some(p) =>
if p.start() {
alog("registering with polkit for this session")
} else {
self.give_up("polkit could not be asked: " + p.error())
}
None => {
ignore(self.link.send(["ready"]))
let (req, desc) = demo_request(self.demo)
alog("demo (" + self.demo + ")")
self.open(req, desc)
}
}
}
///| Tell the compositor why we can't serve, and finish.
fn AgentLoop::give_up(self : AgentLoop, why : String) -> Unit {
alog(why)
ignore(self.link.send(["error", why]))
self.finished = true
self.link.close()
}
///| Show `req`: its words, accounts, and first state; its check starts.
fn AgentLoop::open(self : AgentLoop, req : AuthRequest, desc : Description) -> Unit {
let id = self.next_id.to_string()
self.next_id = self.next_id + 1
self.id = id
let m = AuthMachine::new(req, desc, self.start)
self.machine = Some(m)
alog("request " + id + ": " + req.action_id + " (" + desc.title + ")")
ignore(self.link.send(["request", id, desc.title, desc.subtitle, desc.command, desc.program, req.icon_name, req.message]))
for d in desc.details {
ignore(self.link.send(["detail", id, d.0, d.1]))
}
for u in req.users {
ignore(self.link.send(["user", id, u.name, u.real_name, u.uid.to_string()]))
}
m.begin()
self.send_state()
}
///| Send the state if it changed.
fn AgentLoop::send_state(self : AgentLoop) -> Unit {
match self.machine {
Some(m) => if m.take_changed() { ignore(self.link.send(m.state_fields(self.id))) }
None => ()
}
}
///| The request is over: answer polkit, tell the compositor.
fn AgentLoop::close_request(self : AgentLoop, result : Result[Unit, String]?) -> Unit {
match self.machine {
Some(m) => {
m.cancel()
match (self.polkit, result) {
(Some(p), Some(r)) => p.finish(m.req.cookie, r)
_ => ()
}
alog(
"request " + self.id + " " +
(match result {
Some(Ok(_)) => "authorized"
Some(Err(_)) => "dismissed"
None => "withdrawn by polkit"
}),
)
ignore(self.link.send(["close", self.id]))
self.machine = None
if self.polkit is None {
// The demo shows one request.
self.finished = true
self.link.close()
}
}
None => ()
}
}
///| 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
}
let cmd = field_text(f[0])
let id = field_text(f[1])
let m = match self.machine {
Some(m) if id == self.id => m
_ => {
for b in f {
zero(b)
}
return
}
}
match cmd {
"answer" =>
if f.length() >= 3 {
m.answer(f[2])
}
"user" => m.pick_user(parse_uint(f.get(2).map(field_text).unwrap_or("")).unwrap_or(-1))
"retry" => m.retry()
"cancel" => {
self.close_request(Some(Err("The user dismissed the authentication dialog")))
return
}
_ => ()
}
for b in f {
zero(b)
}
}
///| The fds to wait on.
pub fn AgentLoop::fds(self : AgentLoop) -> Array[Int] {
let out = [self.link.fd()]
match self.polkit {
Some(p) => if p.fd() >= 0 { out.push(p.fd()) }
None => ()
}
match self.machine {
Some(m) => if m.fd() >= 0 { out.push(m.fd()) }
None => ()
}
out
}
///| How long to wait for the fds before stepping anyway (ms; -1: no limit).
pub fn AgentLoop::timeout(self : AgentLoop) -> Int {
match self.machine {
Some(m) if m.needs_timer() => 50
_ => -1
}
}
///| Serve whatever is ready.
pub fn AgentLoop::step(self : AgentLoop) -> Unit {
if self.finished {
return
}
for line in self.link.read_lines() {
self.on_link(line)
}
if self.link.eof {
// The compositor closed the link (the Settings switch, or the session ended).
alog("the compositor closed the link; stopping")
self.shutdown()
return
}
match self.polkit {
Some(p) => {
ignore(p.tick())
if p.registered() && !self.was_registered {
self.was_registered = true
alog("registered: polkit asks this agent for this session's passwords")
ignore(self.link.send(["ready"]))
}
if p.failed() {
self.close_request(None)
self.give_up(
if self.was_registered {
"lost the system bus: " + p.error()
} else {
"polkit refused the agent: " + p.error()
},
)
return
}
match self.machine {
Some(m) => if !p.waiting(m.req.cookie) { self.close_request(None) }
None => ()
}
}
None => ()
}
match self.machine {
Some(m) => {
m.pump()
self.send_state()
if m.phase == Done {
self.close_request(Some(if m.authorized { Ok(()) } else { Err("The user dismissed the authentication dialog") }))
}
}
None => ()
}
if self.machine is None && !self.finished {
match self.polkit {
Some(p) =>
match p.current() {
Some(req) => self.open(req, (self.describe)(req))
None => ()
}
None => ()
}
}
}
///| Stop: dismiss what waits, leave polkit, close the link.
pub fn AgentLoop::shutdown(self : AgentLoop) -> Unit {
match self.machine {
Some(m) => m.cancel()
None => ()
}
self.machine = None
match self.polkit {
Some(p) => p.stop()
None => ()
}
self.link.close()
self.finished = true
}
///| Whether the loop is done.
pub fn AgentLoop::finished(self : AgentLoop) -> Bool {
self.finished
}
///| Run until done (the agent's main).
pub fn AgentLoop::run(self : AgentLoop) -> Unit {
self.start()
while !self.finished {
ignore(@sys.wait_readable(self.fds(), self.timeout()))
self.step()
}
self.link.close()
}