Password dialog: Chandra is its own polkit agent, drawn in the shell layer
CI / test (push) Failing after 18s

run0, pkexec and other polkit prompts used whatever third-party agent was
installed: a plain toolkit window saying "start transient unit
'run-p15802-i1990.service'". The compositor now registers as the session's
polkit authentication agent and asks in its own dialog:

- a centered card over a dimmed screen, above all windows and client menus,
  themed (dark/light follow the Dark mode switch), keyboard-first: Enter,
  Esc, Tab order, Alt+R show/hide, Alt+D details, Ctrl+U clear
- for run0 it shows the command it will run ("gparted /dev/sda", as root)
  from run0's command line (pid from polkit's details or the unit name),
  pkexec's command from its details, polkit's message otherwise; Details
  lists the requester, target user, unit and action id
- account picker when several admins can answer (group members expanded)
- the PAM conversation through polkit-agent-helper-1: polkit 126's socket
  first, else the setuid helper on a socket pair (new sys spawn-socket on the
  native, Rust and MoonBit hosts); password, echo-on prompts, info (fingerprint)
  and errors (faillock) shown as they come; wrong password shakes and retries;
  spinner while PAM checks; Caps Lock warning
- typing through the clients' xkb keymap (groups, Shift, AltGr, Caps Lock),
  US layout when there is none
- no client has keyboard focus or input while it is up; the password is
  wiped after sending and never logged

Settings > Session > "Chandra password dialog" (state.edn :auth-agent
:system when off) switches back to the third-party agent, which
chandra-session now finds and the compositor starts (also when polkit
refuses our agent). Tests: polkit_test (keymaps, helper protocol, run0
parsing, dialog states, the socket-pair route) and auth_test (mock polkit
Authority on a private dbus-daemon, mock helper; CHANDRA_AUTH_SHOTS writes
a PNG per state). Docs: docs/auth-dialog.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgkRPrAzXECBUGmNEE
This commit is contained in:
Claude committed 2026-11-26 00:17:04 +00:00
1 parent 2a67bc83d4
commit 0feea23a06
32 files changed
+3914 -27

No files matched your search

+5
View File
@@ -192,6 +192,9 @@ pub fn run(args : Array[String]) -> Int {
@sys.log("chandra compositor listening on " + socket_path) @sys.log("chandra compositor listening on " + socket_path)
// chandra-ctl's socket (reload panel modules from a script); SIGUSR1 reloads too. // chandra-ctl's socket (reload panel modules from a script); SIGUSR1 reloads too.
ignore(comp.start_control(@host.control_socket_path(@sys.getenv("XDG_RUNTIME_DIR"), socket_path))) ignore(comp.start_control(@host.control_socket_path(@sys.getenv("XDG_RUNTIME_DIR"), socket_path)))
if drm {
comp.start_auth_agent() // polkit's password prompts (run0, pkexec): Chandra's dialog
}
if restore { if restore {
ignore(comp.restore_session()) // reopen the windows the last session ended with ignore(comp.restore_session()) // reopen the windows the last session ended with
} }
@@ -272,6 +275,7 @@ pub fn run(args : Array[String]) -> Int {
if pfd >= 0 { if pfd >= 0 {
fds.push(pfd) fds.push(pfd)
} }
fds.append(comp.auth_fds()) // polkit asking for a password, and its helper
ignore(@sys.wait_readable(fds, idle.timeout())) ignore(@sys.wait_readable(fds, idle.timeout()))
} else { } else {
// Sleep out what is left of the frame budget (8 ms), not a fixed 8 ms on top of the work. // Sleep out what is left of the frame budget (8 ms), not a fixed 8 ms on top of the work.
@@ -291,6 +295,7 @@ pub fn run(args : Array[String]) -> Int {
let mut busy = false let mut busy = false
let wait_fds = comp.server.wait_fds() let wait_fds = comp.server.wait_fds()
wait_fds.append(comp.control_fds()) // chandra-ctl wait_fds.append(comp.control_fds()) // chandra-ctl
wait_fds.append(comp.auth_fds()) // polkit asking for a password, and its helper
match nested { match nested {
Some(n) => { Some(n) => {
if !n.poll() { if !n.poll() {
+4
View File
@@ -123,6 +123,10 @@ fn main {
println("chandra compositor listening on " + socket_path + " (wasi-gfx surface active)") println("chandra compositor listening on " + socket_path + " (wasi-gfx surface active)")
// chandra-ctl's socket (reload panel modules from a script); SIGUSR1 reloads too. // chandra-ctl's socket (reload panel modules from a script); SIGUSR1 reloads too.
ignore(comp.start_control(@host.control_socket_path(@sys.getenv("XDG_RUNTIME_DIR"), socket_path))) ignore(comp.start_control(@host.control_socket_path(@sys.getenv("XDG_RUNTIME_DIR"), socket_path)))
if drm {
comp.login_session = true
comp.start_auth_agent() // polkit's password prompts (run0, pkexec): Chandra's dialog
}
if restore { if restore {
ignore(comp.restore_session()) // reopen the windows the last session ended with ignore(comp.restore_session()) // reopen the windows the last session ended with
} }
+751
View File
@@ -0,0 +1,751 @@
///| The authentication dialog: Chandra's own polkit agent (compositor/polkit) shows it when
/// run0, pkexec or any app needs an administrator's password.
///
/// It is drawn by the compositor above everything, client menus included (they are hidden while
/// it is up), on a dimmed screen, and it takes the keyboard and the pointer: no client gets input
/// or keyboard focus until it closes, and no client can draw over it. Typing goes through the
/// xkb keymap clients get, so the password is typed on the user's layout. The password is kept
/// as characters that are wiped once sent, and is never logged.
///
/// The conversation runs through polkit's helper (HelperSession): its prompts, errors and
/// information messages are shown as they come (fingerprint readers, one-time codes, lockouts).
///| What the dialog needs while it is up.
pub(all) struct AuthUi {
dialog : @polkit.AuthDialog
mut helper : @polkit.HelperSession?
/// The window that had the keyboard before, given it back on close.
prev_kbd : UInt64?
/// The app icon (0: the lock drawn instead).
icon : UInt
/// Where each control was last drawn, for clicks and the cursor.
hits : Array[(@scene.Rect, @polkit.Focus)]
/// When it opened (the spinner's clock).
opened : UInt64
}
///| The dialog that is up, if any.
pub fn ChandraCompositor::auth_dialog(self : ChandraCompositor) -> @polkit.AuthDialog? {
self.auth.map(a => a.dialog)
}
///| Start Chandra's polkit agent, or the system's, per the Settings switch and
/// CHANDRA_POLKIT_AGENT ("none": no agent; a path: that agent). Login session only.
pub fn ChandraCompositor::start_auth_agent(self : ChandraCompositor) -> Unit {
let env = @sys.getenv("CHANDRA_POLKIT_AGENT")
if env == "none" {
return
}
if env != "" && env != "chandra" {
self.spawn_fallback_agent(env)
return
}
if !self.shell.native_auth_agent {
self.spawn_fallback_agent(@sys.getenv("CHANDRA_POLKIT_FALLBACK"))
return
}
let agent = match self.polkit {
Some(a) => a
None => {
let a = @polkit.PolkitAgent::new(bus_path=self.polkit_bus)
self.polkit = Some(a)
a
}
}
if agent.start() {
@sys.log("chandra: registering as the polkit authentication agent")
} else {
@sys.log("chandra: polkit agent not registered (" + agent.error() + ")")
self.polkit = None
self.spawn_fallback_agent(@sys.getenv("CHANDRA_POLKIT_FALLBACK"))
}
}
///| Start a third-party polkit agent (once), when one is installed.
fn ChandraCompositor::spawn_fallback_agent(self : ChandraCompositor, path : String) -> Unit {
if path == "" || self.fallback_agent_started {
return
}
if @sys.spawn(path, self.shell.display) {
self.fallback_agent_started = true
@sys.log("chandra: started polkit agent " + path)
}
}
///| The Settings switch changed: register or leave. Leaving dismisses an open dialog and starts
/// the system's agent (polkit allows one per session); coming back takes effect at the next
/// login when that agent already runs.
pub fn ChandraCompositor::auth_agent_setting_changed(self : ChandraCompositor) -> Unit {
if !self.login_session {
return
}
if self.shell.native_auth_agent {
if self.polkit is None {
self.start_auth_agent()
}
} else {
match self.polkit {
Some(a) => {
self.close_auth(None)
a.stop()
self.polkit = None
self.spawn_fallback_agent(@sys.getenv("CHANDRA_POLKIT_FALLBACK"))
}
None => ()
}
}
}
///| Serve the agent and the helper; open, update and close the dialog. Each main-loop pass.
fn ChandraCompositor::auth_tick(self : ChandraCompositor) -> Unit {
let agent = match self.polkit {
Some(a) => a
None => return
}
let was_registered = agent.registered()
ignore(agent.tick())
if agent.failed() {
if was_registered {
@sys.log("chandra: polkit agent lost the system bus (" + agent.error() + ")")
} else {
@sys.log("chandra: polkit agent not registered (" + agent.error() + ")")
self.spawn_fallback_agent(@sys.getenv("CHANDRA_POLKIT_FALLBACK"))
}
self.close_auth(None)
self.polkit = None
return
}
if agent.registered() && !was_registered {
@sys.log("chandra: polkit authentication agent registered")
}
match self.auth {
Some(ui) =>
if !agent.waiting(ui.dialog.req.cookie) {
// polkitd withdrew it (the asking process went away).
self.close_auth(None)
} else {
self.auth_helper_events(ui)
}
None => ()
}
if self.auth is None {
match agent.current() {
Some(req) => self.open_auth(req)
None => ()
}
}
}
///| Show the dialog for `req` and start the helper.
fn ChandraCompositor::open_auth(self : ChandraCompositor, req : @polkit.AuthRequest) -> Unit {
let desc = match self.auth_describe {
Some(f) => f(req)
None => @polkit.describe(req)
}
let dialog = @polkit.AuthDialog::new(req, desc)
let icon = if desc.program != "" {
self.shell.window_icon(desc.program)
} else if req.icon_name != "" {
self.shell.theme_icon(req.icon_name)
} else {
0U
}
let ui : AuthUi = {
dialog,
helper: None,
prev_kbd: self.kbd_win,
icon,
hits: [],
opened: @sys.monotonic_ms(),
}
self.auth = Some(ui)
// Nothing else gets the keyboard or the pointer while it is up.
self.set_kbd_focus(None)
self.leave_pointer()
self.auth_start_helper(ui)
self.damage.mark_full()
}
///| (Re)start the helper for the selected user.
fn ChandraCompositor::auth_start_helper(self : ChandraCompositor, ui : AuthUi) -> Unit {
match ui.helper {
Some(h) => h.close()
None => ()
}
ui.helper = None
match ui.dialog.user() {
Some(u) => {
let routes = if self.auth_routes.length() > 0 { self.auth_routes } else { @polkit.helper_routes() }
match @polkit.HelperSession::start_any(routes, u.name, ui.dialog.req.cookie) {
Some(h) => ui.helper = Some(h)
None => ui.dialog.error = "polkit's authentication helper could not be started."
}
}
None => ()
}
}
///| Feed what the helper said to the dialog.
fn ChandraCompositor::auth_helper_events(self : ChandraCompositor, ui : AuthUi) -> Unit {
match ui.helper {
Some(h) => {
let evs = h.read()
for ev in evs {
self.auth_effect(ui, ui.dialog.helper(ev, @sys.monotonic_ms()))
if self.auth is None {
return
}
}
if evs.length() > 0 {
self.damage.mark_full()
}
}
None => ()
}
}
///| Carry out what the dialog asked for.
fn ChandraCompositor::auth_effect(self : ChandraCompositor, ui : AuthUi, e : @polkit.DialogEffect) -> Unit {
match e {
Nothing => ()
Answer(b) => {
match ui.helper {
Some(h) => if !h.respond(b) { ui.dialog.error = "The authentication helper stopped." }
None => ()
}
@polkit.zero(b)
}
Restart => self.auth_start_helper(ui)
Cancelled => self.close_auth(Some(Err("The user dismissed the authentication dialog")))
Authorized => self.close_auth(Some(Ok(())))
}
self.damage.mark_full()
}
///| Close the dialog; `result` answers polkitd (None: it is already answered or withdrawn).
fn ChandraCompositor::close_auth(self : ChandraCompositor, result : Result[Unit, String]?) -> Unit {
match self.auth {
Some(ui) => {
ui.dialog.wipe()
match ui.helper {
Some(h) => h.close()
None => ()
}
self.auth = None
match (result, self.polkit) {
(Some(r), Some(a)) => a.finish(ui.dialog.req.cookie, r)
_ => ()
}
match ui.prev_kbd {
Some(w) => if self.windows.contains(w) { self.set_kbd_focus(Some(w)) }
None => ()
}
self.damage.mark_full()
}
None => ()
}
}
///| The keymap typing goes through: the one clients have, else US.
fn ChandraCompositor::auth_keymap(self : ChandraCompositor) -> @polkit.Keymap {
match self.keymap {
Some((src, k)) if physical_equal(src, self.server.keymap) => k
_ => {
let k = @polkit.Keymap::from_text(@utf8.decode_lossy(self.server.keymap))
self.keymap = Some((self.server.keymap, k))
k
}
}
}
///| Input while the dialog is up: all of it is the dialog's. True when it took the event.
fn ChandraCompositor::auth_input(self : ChandraCompositor, ev : @nested.InputEvent) -> Bool {
// Releases of keys the dialog took must not reach the client that gets the keyboard back.
match ev {
Key(code, false) =>
if self.auth_swallow.contains(code) {
self.auth_swallow.retain(c => c != code)
return true
}
_ => ()
}
let ui = match self.auth {
Some(u) => u
None => return false
}
match ev {
Key(code, pressed) => {
if code == key_lsuper || code == key_rsuper {
self.super_solo = false
}
if pressed {
self.auth_swallow.push(code)
let mods = self.mods | self.mods_latched | self.mods_locked
let ch = self.auth_keymap().char_for(code, mods, self.mods_group)
self.auth_effect(ui, ui.dialog.key(code, self.mods, ch))
}
true
}
Modifiers(_, _, lock, _) => {
ui.dialog.caps = (lock & @polkit.mask_lock) != 0U
self.damage.mark_full()
true
}
PointerMove(x, y) => {
self.ptr_x = x
self.ptr_y = y
self.damage.mark_full()
true
}
PointerButton(button, pressed) => {
if pressed && button == 272U {
match self.auth_hit(ui) {
Some(f) => self.auth_effect(ui, ui.dialog.activate(f))
None => ()
}
}
true
}
Scroll(_, _, _) => true
}
}
///| The control under the pointer.
fn ChandraCompositor::auth_hit(self : ChandraCompositor, ui : AuthUi) -> @polkit.Focus? {
let x = self.ptr_x.to_int()
let y = self.ptr_y.to_int()
for h in ui.hits {
let r = h.0
if x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h {
return Some(h.1)
}
}
None
}
///| Cursor over the dialog: a text beam over the field, a hand over buttons, else the arrow.
fn ChandraCompositor::auth_cursor(self : ChandraCompositor, ui : AuthUi) -> UInt {
match self.auth_hit(ui) {
Some(Field) => 9U // text
Some(_) => 4U // pointer
None => 1U // default
}
}
///| Whether the dialog animates (a failed attempt shakes it; a spinner while PAM checks).
fn ChandraCompositor::auth_animating(self : ChandraCompositor) -> Bool {
match self.auth {
Some(ui) => ui.dialog.shaking(@sys.monotonic_ms()) || ui.dialog.phase == Checking
None => false
}
}
///| The fds to wake on: the agent's bus and the helper.
pub fn ChandraCompositor::auth_fds(self : ChandraCompositor) -> Array[Int] {
let out : Array[Int] = []
match self.polkit {
Some(a) => if a.fd() >= 0 { out.push(a.fd()) }
None => ()
}
match self.auth {
Some({ helper: Some(h), .. }) => if h.fd() >= 0 { out.push(h.fd()) }
_ => ()
}
out
}
// ---- drawing ----
///| Colours the palette has no slot for: errors and warnings, readable on the card.
fn auth_colors(p : @scene.ThemePalette) -> (@scene.Rgba, @scene.Rgba) {
// A light card (bright foreground means dark theme).
let dark = p.foreground.r.to_int() + p.foreground.g.to_int() + p.foreground.b.to_int() > 384
if dark {
(@scene.Rgba::from_hex("#f87171"), @scene.Rgba::from_hex("#fbbf24"))
} else {
(@scene.Rgba::from_hex("#c62828"), @scene.Rgba::from_hex("#8a5a00"))
}
}
///| `text` broken into lines no wider than `max_w`, at word boundaries (long words by character).
fn wrap_text(text : String, size : Int, bold : Bool, mono : Bool, max_w : Int) -> Array[String] {
let out : Array[String] = []
for para in text.split("\n") {
let mut line = ""
for w in para.split(" ") {
let word = w.to_string()
let cand = if line == "" { word } else { line + " " + word }
if @renderer.text_width(cand, size, bold, mono) <= max_w {
line = cand
continue
}
if line != "" {
out.push(line)
line = ""
}
// A word wider than the line: split it.
let mut part = ""
for c in word {
let next = part + c.to_string()
if @renderer.text_width(next, size, bold, mono) > max_w && part != "" {
out.push(part)
part = c.to_string()
} else {
part = next
}
}
line = part
}
out.push(line)
}
out
}
///| A padlock, for requests without an app icon.
fn lock_glyph(x : Int, y : Int, s : Int, c : @scene.Rgba, bg : @scene.Rgba, ops : Array[@scene.DrawOp]) -> Unit {
let bw = s * 5 / 8
let bh = s / 2
let bx = x + (s - bw) / 2
let by = y + s - bh - s / 10
let sw = bw * 5 / 8
let shx = x + (s - sw) / 2
ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(shx, by - bh * 3 / 4, sw, bh), c, s / 12 + 1, sw / 2))
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(bx, by, bw, bh), c, s / 10))
ops.push(@scene.DrawOp::Circle(x + s / 2, by + bh * 2 / 5, s / 14 + 1, bg, true))
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(x + s / 2 - 1, by + bh * 2 / 5, 3, bh / 3), bg, 1))
}
///| A button: filled (the default action) or outlined; with a focus ring.
fn auth_button(
r : @scene.Rect,
label : String,
primary : Bool,
focused : Bool,
hover : Bool,
enabled : Bool,
p : @scene.ThemePalette,
fs : Int,
rad : Int,
ops : Array[@scene.DrawOp],
) -> Unit {
if primary {
let a = p.accent
let alpha = if enabled { if hover { 230 } else { 255 } } else { 120 }
ops.push(@scene.DrawOp::FillRect(r, @scene.Rgba::new(a.r.to_int(), a.g.to_int(), a.b.to_int(), alpha), rad))
ops.push(@scene.DrawOp::Text(r.x + r.w / 2, r.y + r.h / 2, label, fs, p.accent_foreground, @scene.TextAlign::Center, true))
} else {
if hover {
ops.push(@scene.DrawOp::FillRect(r, p.surface_hover, rad))
}
ops.push(@scene.DrawOp::StrokeRect(r, p.border, 1, rad))
ops.push(@scene.DrawOp::Text(r.x + r.w / 2, r.y + r.h / 2, label, fs, p.foreground, @scene.TextAlign::Center, false))
}
if focused {
ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(r.x - 3, r.y - 3, r.w + 6, r.h + 6), p.accent, 2, rad + 3))
}
}
///| A right-pointing (`down`: down-pointing) chevron centred at (cx, cy).
fn chevron(cx : Int, cy : Int, s : Int, down : Bool, left : Bool, c : @scene.Rgba, ops : Array[@scene.DrawOp]) -> Unit {
if down {
ops.push(@scene.DrawOp::Line(cx - s, cy - s / 2, cx, cy + s / 2, c, 2))
ops.push(@scene.DrawOp::Line(cx, cy + s / 2, cx + s, cy - s / 2, c, 2))
} else if left {
ops.push(@scene.DrawOp::Line(cx + s / 2, cy - s, cx - s / 2, cy, c, 2))
ops.push(@scene.DrawOp::Line(cx - s / 2, cy, cx + s / 2, cy + s, c, 2))
} else {
ops.push(@scene.DrawOp::Line(cx - s / 2, cy - s, cx + s / 2, cy, c, 2))
ops.push(@scene.DrawOp::Line(cx + s / 2, cy, cx - s / 2, cy + s, c, 2))
}
}
///| Draw the dialog (everything below it dimmed) and note where its controls are.
fn ChandraCompositor::auth_ops(self : ChandraCompositor) -> Array[@scene.DrawOp] {
let ops : Array[@scene.DrawOp] = []
let ui = match self.auth {
Some(u) => u
None => return ops
}
let d = ui.dialog
let now = @sys.monotonic_ms()
let p = self.theme.palette
let (err_c, warn_c) = auth_colors(p)
let fs = self.theme.font_size
let rad = self.theme.radius + 2
let sw = self.output_w
let sh = self.output_h
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(0, 0, sw, sh), @scene.Rgba::new(0, 0, 0, 150), 0))
let w = (sw - 32).min(460)
let pad = 24
let inner = w - pad * 2
let hover = self.auth_hit(ui)
// Lay out top to bottom into `body` (card-relative y), then place the card.
let body : Array[@scene.DrawOp] = []
let hits : Array[(@scene.Rect, @polkit.Focus)] = []
let mut y = pad
// Header: icon, overline, title, subtitle.
let icon_s = 48
let tx = pad + icon_s + 16
let tw = w - tx - pad
let header_top = y
let mut hy = y
body.push(@scene.DrawOp::Text(tx, hy + 7, "AUTHENTICATION REQUIRED", fs - 3, p.accent, @scene.TextAlign::Left, true))
hy = hy + 18
let title_lines = wrap_text(d.desc.title, fs + 3, true, false, tw)
for l in title_lines {
body.push(@scene.DrawOp::Text(tx, hy + (fs + 8) / 2, l, fs + 3, p.foreground, @scene.TextAlign::Left, true))
hy = hy + fs + 8
}
hy = hy + 2
for l in wrap_text(d.desc.subtitle, fs - 1, false, false, tw) {
body.push(@scene.DrawOp::Text(tx, hy + (fs + 4) / 2, l, fs - 1, p.foreground_muted, @scene.TextAlign::Left, false))
hy = hy + fs + 4
}
// Icon tile.
let ix = pad
let iy = header_top + 2
body.push(@scene.DrawOp::FillRect(@scene.Rect::new(ix, iy, icon_s, icon_s), p.surface_hover, 12))
if ui.icon != 0U {
body.push(@scene.DrawOp::Image(@scene.Rect::new(ix + 6, iy + 6, icon_s - 12, icon_s - 12), ui.icon))
} else {
lock_glyph(ix + 8, iy + 8, icon_s - 16, p.accent, p.surface_hover, body)
}
y = hy.max(iy + icon_s) + 14
// The command, as a shell would read it.
if d.desc.command != "" {
let mfs = fs - 1
let lines = wrap_text(d.desc.command, mfs, false, true, inner - 24)
let shown = if lines.length() > 4 { lines[:4].to_array() } else { lines }
if lines.length() > 4 {
shown[3] = shown[3] + " …"
}
let lh = mfs + 6
let bh = shown.length() * lh + 16
body.push(@scene.DrawOp::FillRect(@scene.Rect::new(pad, y, inner, bh), p.surface_hover, rad))
body.push(@scene.DrawOp::FillRect(@scene.Rect::new(pad, y, 3, bh), p.accent, 1))
for i, l in shown {
body.push(@scene.DrawOp::MonoText(pad + 14, y + 8 + i * lh + lh / 2, l, mfs, p.foreground, @scene.TextAlign::Left, false))
}
y = y + bh + 14
}
// Who authenticates.
match d.user() {
Some(u) => {
let rh = 40
let r = @scene.Rect::new(pad, y, inner, rh)
let many = d.req.users.length() > 1
if many {
if hover == Some(User) {
body.push(@scene.DrawOp::FillRect(r, p.surface_hover, rad))
}
hits.push((r, User))
}
let initial = if u.real_name != "" { u.real_name[:1].to_string() } else { u.name[:1].to_string() }
body.push(@scene.DrawOp::Circle(pad + 20, y + rh / 2, 15, p.accent, true))
body.push(@scene.DrawOp::Text(pad + 20, y + rh / 2, initial.to_upper(), fs, p.accent_foreground, @scene.TextAlign::Center, true))
let name = if u.real_name != "" && u.real_name != u.name { u.real_name } else { u.name }
body.push(@scene.DrawOp::Text(pad + 44, y + rh / 2 - 8, name, fs, p.foreground, @scene.TextAlign::Left, true))
let login = if u.uid == 0 { "root" } else { u.name }
let sub = if many {
login + " · account " + (d.user_sel + 1).to_string() + " of " + d.req.users.length().to_string()
} else {
login
}
body.push(@scene.DrawOp::Text(pad + 44, y + rh / 2 + 9, sub, fs - 2, p.foreground_muted, @scene.TextAlign::Left, false))
if many {
chevron(pad + inner - 34, y + rh / 2, 5, false, true, p.foreground_muted, body)
chevron(pad + inner - 14, y + rh / 2, 5, false, false, p.foreground_muted, body)
if d.focus == User {
body.push(@scene.DrawOp::StrokeRect(r, p.accent, 2, rad))
}
}
y = y + rh + 12
}
None => ()
}
// The prompt and the field.
body.push(@scene.DrawOp::Text(pad, y + 7, d.prompt, fs - 1, p.foreground_muted, @scene.TextAlign::Left, true))
y = y + 20
let fh = 40
let field = @scene.Rect::new(pad, y, inner, fh)
let enabled = d.phase != Checking
body.push(@scene.DrawOp::FillRect(field, p.surface, rad))
let edge = if d.error != "" && d.typed() == 0 { err_c } else if d.focus == Field { p.accent } else { p.border }
body.push(@scene.DrawOp::StrokeRect(field, edge, if d.focus == Field || d.error != "" { 2 } else { 1 }, rad))
hits.push((@scene.Rect::new(pad, y, inner - 70, fh), Field))
// Show / Hide (not for prompts that show the answer anyway).
let text_right = if d.echo { pad + inner - 12 } else { pad + inner - 76 }
if !d.echo {
let rr = @scene.Rect::new(pad + inner - 68, y + 6, 60, fh - 12)
if hover == Some(Reveal) || d.focus == Reveal {
body.push(@scene.DrawOp::FillRect(rr, p.surface_hover, rad - 2))
}
if d.focus == Reveal {
body.push(@scene.DrawOp::StrokeRect(rr, p.accent, 2, rad - 2))
}
body.push(@scene.DrawOp::Text(rr.x + rr.w / 2, rr.y + rr.h / 2, if d.reveal { "Hide" } else { "Show" }, fs - 1, p.accent, @scene.TextAlign::Center, true))
hits.push((rr, Reveal))
}
body.push(@scene.DrawOp::PushClip(@scene.Rect::new(pad + 8, y, text_right - pad - 8, fh)))
let cy = y + fh / 2
let mut caret_x = pad + 13
if d.typed() == 0 {
let hint = match d.phase {
Starting => "Preparing…"
Waiting => "Waiting…"
_ => if d.echo { "Type your answer" } else { "Type your password" }
}
body.push(@scene.DrawOp::Text(pad + 18, cy, hint, fs, @scene.Rgba::new(p.foreground_muted.r.to_int(), p.foreground_muted.g.to_int(), p.foreground_muted.b.to_int(), 150), @scene.TextAlign::Left, false))
} else if d.echo || d.reveal {
// Keep the end of long text in view.
let t = d.field_text()
let tw2 = @renderer.text_width(t, fs + 1, false, false)
let avail = text_right - pad - 22
let x0 = if tw2 > avail { pad + 14 - (tw2 - avail) } else { pad + 14 }
body.push(@scene.DrawOp::Text(x0, cy, t, fs + 1, if enabled { p.foreground } else { p.foreground_muted }, @scene.TextAlign::Left, false))
caret_x = x0 + tw2 + 2
} else {
let n = d.typed()
let step = 14
let avail = text_right - pad - 22
let total = n * step
let x0 = if total > avail { pad + 14 - (total - avail) } else { pad + 14 }
for i = 0; i < n; i = i + 1 {
body.push(@scene.DrawOp::Circle(x0 + i * step + 5, cy, 4, if enabled { p.foreground } else { p.foreground_muted }, true))
}
caret_x = x0 + total + 2
}
if d.focus == Field && enabled {
body.push(@scene.DrawOp::FillRect(@scene.Rect::new(caret_x, cy - fs / 2 - 2, 2, fs + 4), p.accent, 0))
}
body.push(@scene.DrawOp::PopClip)
y = y + fh + 10
// Status: busy, Caps Lock, error, PAM's information.
let status : Array[(String, @scene.Rgba, Bool)] = []
if d.phase == Checking {
status.push(("Checking…", p.foreground_muted, true))
}
if d.caps && !d.echo {
status.push(("Caps Lock is on", warn_c, false))
}
if d.error != "" {
status.push((d.error, err_c, false))
}
if d.info != "" {
status.push((d.info, p.foreground, false))
}
for s in status {
let lines = wrap_text(s.0, fs - 1, false, false, inner - 22)
// A marker: a spinner while busy, else a dot in the line's colour.
if s.2 {
let t = ((now - ui.opened) / 90UL).to_int()
for k = 0; k < 8; k = k + 1 {
let ang = (k + t) % 8
let (dx, dy) = match ang {
0 => (0, -6)
1 => (4, -4)
2 => (6, 0)
3 => (4, 4)
4 => (0, 6)
5 => (-4, 4)
6 => (-6, 0)
_ => (-4, -4)
}
let a = 50 + k * 29
body.push(@scene.DrawOp::Circle(pad + 6 + dx, y + 9 + dy, 2, @scene.Rgba::new(p.accent.r.to_int(), p.accent.g.to_int(), p.accent.b.to_int(), a), true))
}
} else {
body.push(@scene.DrawOp::Circle(pad + 6, y + 9, 3, s.1, true))
}
for l in lines {
body.push(@scene.DrawOp::Text(pad + 18, y + 9, l, fs - 1, s.1, @scene.TextAlign::Left, false))
y = y + fs + 5
}
y = y + 3
}
y = y + 6
// Details.
if d.details_open {
let rows : Array[(String, String)] = d.desc.details.copy()
if d.req.message != "" && d.desc.title != d.req.message {
rows.push(("polkit says", d.req.message))
}
let lw = 104
let dh0 = y
y = y + 10
let rows_ops : Array[@scene.DrawOp] = []
for r in rows {
let vl = wrap_text(r.1, fs - 2, false, r.0 == "Action" || r.0 == "Unit", inner - lw - 24)
rows_ops.push(@scene.DrawOp::Text(pad + 12, y + 8, r.0, fs - 2, p.foreground_muted, @scene.TextAlign::Left, true))
for l in vl {
if r.0 == "Action" || r.0 == "Unit" {
rows_ops.push(@scene.DrawOp::MonoText(pad + 12 + lw, y + 8, l, fs - 2, p.foreground, @scene.TextAlign::Left, false))
} else {
rows_ops.push(@scene.DrawOp::Text(pad + 12 + lw, y + 8, l, fs - 2, p.foreground, @scene.TextAlign::Left, false))
}
y = y + fs + 3
}
y = y + 4
}
y = y + 6
body.push(@scene.DrawOp::FillRect(@scene.Rect::new(pad, dh0, inner, y - dh0), p.surface_hover, rad))
body.append(rows_ops)
y = y + 12
}
// Bottom row: Details toggle on the left, Cancel and Authenticate on the right.
let bh = 36
let dl = if d.details_open { "Hide details" } else { "Details" }
let dw = @renderer.text_width(dl, fs - 1, false, false) + 30
let dr = @scene.Rect::new(pad - 6, y, dw, bh)
if hover == Some(Details) {
body.push(@scene.DrawOp::FillRect(dr, p.surface_hover, rad))
}
chevron(pad + 6, y + bh / 2, 4, d.details_open, false, p.foreground_muted, body)
body.push(@scene.DrawOp::Text(pad + 18, y + bh / 2, dl, fs - 1, p.foreground_muted, @scene.TextAlign::Left, false))
if d.focus == Details {
body.push(@scene.DrawOp::StrokeRect(dr, p.accent, 2, rad))
}
hits.push((dr, Details))
let allow_w = @renderer.text_width("Authenticate", fs, true, false) + 32
let cancel_w = @renderer.text_width("Cancel", fs, false, false) + 32
let ar = @scene.Rect::new(pad + inner - allow_w, y, allow_w, bh)
let cr = @scene.Rect::new(ar.x - 10 - cancel_w, y, cancel_w, bh)
auth_button(cr, "Cancel", false, d.focus == Cancel, hover == Some(Cancel), true, p, fs, rad, body)
auth_button(ar, "Authenticate", true, d.focus == Allow, hover == Some(Allow), enabled && (d.typed() > 0 || d.echo), p, fs, rad, body)
hits.push((cr, Cancel))
hits.push((ar, Allow))
y = y + bh + pad
// Place the card in the middle (shaking after a failure) with a soft shadow.
let h = y
let cx = (sw - w) / 2 + d.shake_offset(now)
let cyy = ((sh - h) / 2).max(8)
for k = 1; k <= 4; k = k + 1 {
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(cx - k * 2, cyy - k * 2 + 6, w + k * 4, h + k * 4), @scene.Rgba::new(0, 0, 0, 22), rad + 6 + k * 2))
}
let opaque = @scene.Rgba::new(p.surface_popup.r.to_int(), p.surface_popup.g.to_int(), p.surface_popup.b.to_int(), 255)
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(cx, cyy, w, h), opaque, rad + 6))
ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(cx, cyy, w, h), p.border, 1, rad + 6))
ops.append(offset_ops_all(body, cx, cyy))
ui.hits.clear()
for hit in hits {
let r = hit.0
ui.hits.push((@scene.Rect::new(r.x + cx, r.y + cyy, r.w, r.h), hit.1))
}
ops
}
///| Move every op by (dx, dy).
fn offset_ops_all(ops : Array[@scene.DrawOp], dx : Int, dy : Int) -> Array[@scene.DrawOp] {
let mv = fn(r : @scene.Rect) { @scene.Rect::new(r.x + dx, r.y + dy, r.w, r.h) }
ops.map(op => match op {
FillRect(r, c, rad) => @scene.DrawOp::FillRect(mv(r), c, rad)
StrokeRect(r, c, w, rad) => @scene.DrawOp::StrokeRect(mv(r), c, w, rad)
Line(x0, y0, x1, y1, c, w) => @scene.DrawOp::Line(x0 + dx, y0 + dy, x1 + dx, y1 + dy, c, w)
Circle(x, y, r, c, f) => @scene.DrawOp::Circle(x + dx, y + dy, r, c, f)
Text(x, y, t, s, c, a, b) => @scene.DrawOp::Text(x + dx, y + dy, t, s, c, a, b)
MonoText(x, y, t, s, c, a, b) => @scene.DrawOp::MonoText(x + dx, y + dy, t, s, c, a, b)
PushClip(r) => @scene.DrawOp::PushClip(mv(r))
PopClip => PopClip
Image(r, h) => @scene.DrawOp::Image(mv(r), h)
})
}
+424
View File
@@ -0,0 +1,424 @@
///| Chandra's polkit agent and its dialog, against a mock polkit Authority on a private bus
/// (a real dbus-daemon) and a mock polkit-agent-helper-1 on a socket (the protocol polkit 126's
/// socket-activated helper speaks). Set CHANDRA_AUTH_SHOTS to a folder to get a PNG of each
/// dialog state.
///| A private message bus for the test (dbus-daemon's session config), its socket path.
fn auth_bus(tag : String) -> String? {
let path = "/tmp/chandra-auth-bus-" + tag + "-" + @sys.getpid().to_string()
@sys.unlink(path)
if !@sys.has_exe("dbus-daemon") {
return None
}
ignore(
@sys.spawn(
"exec timeout 300 dbus-daemon --config-file=/usr/share/dbus-1/session.conf --address=unix:path=" + path + " --nofork --nopidfile </dev/null >/dev/null 2>&1",
"",
),
)
for i = 0; i < 100; i = i + 1 {
let fd = @sys.unix_connect(path)
if fd >= 0 {
@sys.close_fd(fd)
return Some(path)
}
@sys.sleep_ms(20)
}
None
}
///| The mock polkitd: owns org.freedesktop.PolicyKit1, records the agent that registers, and
/// collects answers to the BeginAuthentication calls it makes.
struct MockAuthority {
bus : @network.DBus
mut agent : String
/// Error to answer RegisterAuthenticationAgent with ("" accepts).
mut refuse : String
/// Answers to BeginAuthentication: "ok" or the error name.
answers : Array[String]
}
///|
fn MockAuthority::new(path : String) -> MockAuthority {
let bus = @network.DBus::open(path).unwrap()
let r = bus.call_sync(
@network.DMessage::call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "RequestName", [
Str("org.freedesktop.PolicyKit1"),
U32(4),
]),
1000,
)
guard r is Some({ body: [U32(1U)], .. }) else { abort("could not own org.freedesktop.PolicyKit1") }
let a = { bus, agent: "", refuse: "", answers: [] }
bus.set_on_call(fn(m) {
match m.meth {
"RegisterAuthenticationAgent" =>
if a.refuse != "" {
bus.reply_error(m, "org.freedesktop.PolicyKit1.Error.Failed", a.refuse)
} else {
match m.body {
[Struct([Str("unix-session"), _]), Str(_), Str(p)] if p == @polkit.agent_path => {
a.agent = m.sender
bus.reply(m, [])
}
_ => bus.reply_error(m, "org.freedesktop.PolicyKit1.Error.Failed", "bad registration")
}
}
"UnregisterAuthenticationAgent" => bus.reply(m, [])
_ => bus.reply_error(m, "org.freedesktop.DBus.Error.UnknownMethod", m.meth)
}
})
a
}
///| Ask the agent to authenticate, like polkitd does for run0.
fn MockAuthority::begin(self : MockAuthority, cookie : String, details : Array[(String, String)]) -> Unit {
let ids : Array[@network.DValue] = [
Struct([Str("unix-user"), @network.dict("v", [("uid", Variant(U32(1000)))])]),
Struct([Str("unix-group"), @network.dict("v", [("gid", Variant(U32(10)))])]),
]
ignore(
self.bus.call(
@network.DMessage::call(self.agent, @polkit.agent_path, @polkit.agent_iface, "BeginAuthentication", [
Str("org.freedesktop.systemd1.manage-units"),
Str("Authentication is required to start transient unit 'run-p15802-i1990.service'."),
Str(""),
@network.DValue::Arr("{ss}", details.map(d => @network.DValue::Entry(Str(d.0), Str(d.1)))),
Str(cookie),
Arr("(sa{sv})", ids),
]),
on_reply=fn(m) {
self.answers.push(if m.mtype == @network.method_return { "ok" } else { m.error_name })
},
),
)
}
///| Users the identities stand for, without reading this machine's /etc/passwd.
fn fake_request(args : Array[@network.DValue]) -> @polkit.AuthRequest? {
let passwd = @polkit.parse_passwd("root:x:0:0:root:/root:/bin/sh\nnandi:x:1000:1000:Nandi Devi:/home/nandi:/bin/bash\nada:x:1001:1001:Ada Lovelace:/home/ada:/bin/sh\n")
let groups = @polkit.parse_group("wheel:x:10:ada,nandi\n")
match args {
[Str(action_id), Str(message), Str(icon_name), details, Str(cookie), Arr(_, ids)] =>
Some({
action_id,
message,
icon_name,
details: @polkit.string_dict(details),
cookie,
users: @polkit.users_for_identities(ids, passwd, groups, 1000),
})
_ => None
}
}
///| A compositor with the agent on `bus` and the helper at `helper` (a socket we listen on).
fn auth_comp(tag : String, bus : String, helper : String) -> @host.ChandraCompositor {
let comp = new_comp("auth-" + tag)
comp.auth_routes = [Socket(helper)]
comp.auth_describe = Some(fn(req) {
@polkit.describe(
req,
cmdline=pid => if pid == 15802 { ["run0", "gparted", "/dev/nvme0n1"] } else { [] },
who=pid => "run0 (pid " + pid.to_string() + "), started from konsole",
)
})
let subject = @network.DValue::Struct([Str("unix-session"), @network.dict("v", [("session-id", Variant(Str("2")))])])
comp.polkit = Some(@polkit.PolkitAgent::new(bus_path=bus, subject~, make_request=fake_request))
comp.start_auth_agent()
comp
}
///| Run both ends until `cond` holds (or about two seconds pass).
fn settle(comp : @host.ChandraCompositor, a : MockAuthority, cond : () -> Bool) -> Bool {
for i = 0; i < 200; i = i + 1 {
a.bus.pump()
comp.step()
if cond() {
return true
}
@sys.sleep_ms(10)
}
false
}
///| The mock helper's side of one session: accept, read the user and cookie lines.
fn helper_accept(listen : Int, comp : @host.ChandraCompositor, a : MockAuthority) -> (Int, String) {
let fd : Ref[Int] = { val: -1 }
ignore(settle(comp, a, fn() {
if fd.val < 0 {
fd.val = @sys.unix_accept(listen)
}
fd.val >= 0
}))
if fd.val < 0 {
abort("no helper connection")
}
(fd.val, helper_lines(fd.val, 2))
}
///| Read `n` lines from the agent (joined with '|').
fn helper_lines(fd : Int, n : Int) -> String {
let buf : FixedArray[Byte] = FixedArray::make(1024, b'\x00')
let got : Array[Byte] = []
let mut lines = 0
for i = 0; i < 100 && lines < n; i = i + 1 {
if @sys.poll_read(fd, 20) > 0 {
let (k, _) = @sys.recvmsg_fd(fd, buf, buf.length())
if k <= 0 {
break
}
for j = 0; j < k; j = j + 1 {
got.push(buf[j])
if buf[j] == b'\n' {
lines = lines + 1
}
}
}
}
@utf8.decode_lossy(Bytes::from_array(got)).trim(chars="\n").to_string().replace_all(old="\n", new="|")
}
///| The helper says `line`.
fn helper_say(fd : Int, line : String) -> Unit {
ignore(@sys.sendmsg_fd(fd, @utf8.encode(line + "\n"), -1))
}
///| Type `s` on the US layout (letters, digits; Shift for capitals).
fn auth_type(comp : @host.ChandraCompositor, s : String) -> Unit {
let rows = [(16U, "qwertyuiop"), (30U, "asdfghjkl"), (44U, "zxcvbnm"), (2U, "1234567890")]
for c in s {
let lower = c.to_string().to_lower()
for r in rows {
match r.1.find(lower) {
Some(i) => {
let code = r.0 + i.reinterpret_as_uint()
let up = lower != c.to_string()
if up {
comp.handle_input(@nested.InputEvent::Modifiers(1U, 0U, 0U, 0U), 1U)
}
comp.handle_input(@nested.InputEvent::Key(code, true), 1U)
comp.handle_input(@nested.InputEvent::Key(code, false), 1U)
if up {
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 1U)
}
break
}
None => ()
}
}
}
}
///|
fn auth_press(comp : @host.ChandraCompositor, code : UInt) -> Unit {
comp.handle_input(@nested.InputEvent::Key(code, true), 1U)
comp.handle_input(@nested.InputEvent::Key(code, false), 1U)
}
///| Save the screen as `<CHANDRA_AUTH_SHOTS>/<name>.png` when that is set.
fn auth_shot(comp : @host.ChandraCompositor, name : String) -> Unit {
let dir = @sys.getenv("CHANDRA_AUTH_SHOTS")
if dir == "" {
return
}
match comp.auth_dialog() {
Some(d) => d.shake_at = 0UL // the card at rest
None => ()
}
comp.damage.mark_full()
let px = comp.compose_frame()
ignore(@sys.mkdir_p(dir))
ignore(@sys.write_file_bytes(dir + "/" + name + ".png", @renderer.encode_png_compressed(px)))
}
///|
let run0_details : Array[(String, String)] = [
("unit", "run-p15802-i1990.service"),
("verb", "start"),
("polkit.subject-pid", "15802"),
("polkit.caller-pid", "1"),
]
///|
test "polkit asks for run0: the dialog shows the command, a wrong password shakes, the right one authorizes" {
let bus = match auth_bus("ok") {
Some(b) => b
None => return // no dbus-daemon here
}
let a = MockAuthority::new(bus)
let hpath = "/tmp/chandra-auth-helper-ok-" + @sys.getpid().to_string()
let listen = @sys.unix_listen(hpath)
let comp = auth_comp("ok", bus, hpath)
assert_true(settle(comp, a, fn() { comp.polkit.map(p => p.registered()).unwrap_or(false) }))
assert_true(a.agent != "")
a.begin("cookie-1", run0_details)
assert_true(settle(comp, a, fn() { comp.auth_dialog() is Some(_) }))
let d = comp.auth_dialog().unwrap()
assert_eq(d.desc.title, "Run a command as root")
assert_eq(d.desc.command, "gparted /dev/nvme0n1")
// The user at the screen comes first; the wheel group adds ada.
assert_eq(d.req.users.map(u => u.name), ["nandi", "ada"])
// The helper is asked for nandi with polkit's cookie.
let (h, hello) = helper_accept(listen, comp, a)
assert_eq(hello, "nandi|cookie-1")
auth_shot(comp, "01-starting")
helper_say(h, "PAM_PROMPT_ECHO_OFF Password: ")
assert_true(settle(comp, a, fn() { d.phase == Prompt }))
auth_shot(comp, "02-idle")
auth_type(comp, "Hunter2")
assert_eq(d.typed(), 7)
auth_shot(comp, "03-typing")
// Caps Lock on shows a warning.
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 2U, 0U), 1U)
assert_true(d.caps)
auth_shot(comp, "04-caps-lock")
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 1U)
auth_press(comp, 28U) // Enter
assert_eq(helper_lines(h, 1), "Hunter2")
assert_eq(d.phase, Checking)
auth_shot(comp, "05-busy")
// Wrong: the helper fails and exits; the dialog says so and starts a new session.
helper_say(h, "FAILURE")
@sys.close_fd(h)
assert_true(settle(comp, a, fn() { d.failures == 1 }))
assert_eq(d.error, "Wrong password. Try again.")
let (h2, hello2) = helper_accept(listen, comp, a)
assert_eq(hello2, "nandi|cookie-1")
helper_say(h2, "PAM_PROMPT_ECHO_OFF Password: ")
assert_true(settle(comp, a, fn() { d.phase == Prompt }))
auth_shot(comp, "06-wrong-password")
// Details, then the right password.
comp.handle_input(@nested.InputEvent::Modifiers(8U, 0U, 0U, 0U), 1U)
auth_press(comp, 32U) // Alt+D
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 1U)
assert_true(d.details_open)
auth_type(comp, "hunter2")
auth_shot(comp, "07-details")
// Revealed text, then the light theme.
comp.handle_input(@nested.InputEvent::Modifiers(8U, 0U, 0U, 0U), 1U)
auth_press(comp, 19U) // Alt+R
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 1U)
assert_true(d.reveal)
auth_shot(comp, "08-revealed")
comp.theme = @scene.ThemeTokens::moon_day()
auth_shot(comp, "09-light")
comp.handle_input(@nested.InputEvent::Modifiers(8U, 0U, 0U, 0U), 1U)
auth_press(comp, 19U)
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 1U)
auth_press(comp, 32U) // Alt is up: 'd' goes into the field
auth_press(comp, 14U) // and Backspace takes it out
auth_shot(comp, "10-light-details")
auth_press(comp, 96U) // keypad Enter
assert_eq(helper_lines(h2, 1), "hunter2")
helper_say(h2, "SUCCESS")
assert_true(settle(comp, a, fn() { comp.auth_dialog() is None }))
assert_true(settle(comp, a, fn() { a.answers.length() == 1 }))
assert_eq(a.answers, ["ok"])
// Key releases after the dialog closed don't leak to clients (nothing swallowed is left).
assert_eq(comp.auth_swallow.length(), 0)
@sys.close_fd(h2)
@sys.close_fd(listen)
@sys.unlink(hpath)
comp.close()
}
///|
test "Escape dismisses: polkitd hears Cancelled; polkitd withdrawing a request closes the dialog" {
let bus = match auth_bus("cancel") {
Some(b) => b
None => return
}
let a = MockAuthority::new(bus)
let hpath = "/tmp/chandra-auth-helper-cancel-" + @sys.getpid().to_string()
let listen = @sys.unix_listen(hpath)
let comp = auth_comp("cancel", bus, hpath)
assert_true(settle(comp, a, fn() { comp.polkit.map(p => p.registered()).unwrap_or(false) }))
a.begin("c1", run0_details)
a.begin("c2", [])
assert_true(settle(comp, a, fn() { comp.auth_dialog() is Some(_) }))
let (h, _) = helper_accept(listen, comp, a)
// A fingerprint reader: PAM informs and waits.
helper_say(h, "PAM_TEXT_INFO Place your finger on the fingerprint reader")
assert_true(settle(comp, a, fn() { comp.auth_dialog().map(d => d.phase == Waiting).unwrap_or(false) }))
auth_shot(comp, "11-fingerprint")
// Two accounts can answer: Tab to the picker, Right picks ada and restarts the helper.
auth_press(comp, 15U)
auth_press(comp, 106U)
assert_eq(comp.auth_dialog().unwrap().user().map(u => u.name), Some("ada"))
let (h2, hello) = helper_accept(listen, comp, a)
assert_eq(hello, "ada|c1")
helper_say(h2, "PAM_PROMPT_ECHO_OFF Password: ")
assert_true(settle(comp, a, fn() { comp.auth_dialog().map(d => d.phase == Prompt).unwrap_or(false) }))
auth_shot(comp, "12-other-account")
auth_press(comp, 1U) // Escape
assert_true(settle(comp, a, fn() { a.answers.length() == 1 }))
assert_eq(a.answers, ["org.freedesktop.PolicyKit1.Error.Cancelled"])
// The second request comes up next; polkitd withdraws it.
assert_true(settle(comp, a, fn() { comp.auth_dialog().map(d => d.req.cookie == "c2").unwrap_or(false) }))
let d2 = comp.auth_dialog().unwrap()
assert_eq(d2.desc.title, "Run a command as root") // the unit name in the message still finds run0
ignore(a.bus.call(@network.DMessage::call(a.agent, @polkit.agent_path, @polkit.agent_iface, "CancelAuthentication", [Str("c2")])))
assert_true(settle(comp, a, fn() { comp.auth_dialog() is None }))
assert_true(settle(comp, a, fn() { a.answers.length() == 2 }))
assert_eq(a.answers[1], "org.freedesktop.PolicyKit1.Error.Cancelled")
@sys.close_fd(h)
@sys.close_fd(h2)
@sys.close_fd(listen)
@sys.unlink(hpath)
comp.close()
}
///|
test "another agent already has the session: ours steps aside" {
let bus = match auth_bus("refuse") {
Some(b) => b
None => return
}
let a = MockAuthority::new(bus)
a.refuse = "An authentication agent already exists for the given subject"
let comp = auth_comp("refuse", bus, "/nonexistent")
assert_true(settle(comp, a, fn() { comp.polkit is None }))
comp.close()
}
///|
test "the helper can't be reached: the dialog says so instead of hanging" {
let bus = match auth_bus("nohelper") {
Some(b) => b
None => return
}
let a = MockAuthority::new(bus)
let comp = auth_comp("nohelper", bus, "/nonexistent/helper.socket")
assert_true(settle(comp, a, fn() { comp.polkit.map(p => p.registered()).unwrap_or(false) }))
a.begin("c1", run0_details)
assert_true(settle(comp, a, fn() { comp.auth_dialog() is Some(_) }))
assert_eq(comp.auth_dialog().unwrap().error, "polkit's authentication helper could not be started.")
// Clicking Cancel dismisses it.
ignore(comp.compose_frame())
let ui = comp.auth.unwrap()
let cancel = ui.hits.filter(h => h.1 == Cancel)[0].0
comp.handle_input(@nested.InputEvent::PointerMove((cancel.x + 5).to_double(), (cancel.y + 5).to_double()), 1U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, true), 2U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 3U)
assert_true(settle(comp, a, fn() { a.answers.length() == 1 }))
assert_true(comp.auth_dialog() is None)
comp.close()
}
///|
test "Settings > Session lists the password dialog switch, saved as :auth-agent :system when off" {
let comp = new_comp("auth-setting")
assert_true(comp.shell.native_auth_agent)
assert_true(comp.shell.open_settings(Session))
ignore(comp.compose_frame())
let slot = comp.shell.slot_of("session-settings")
assert_true(comp.shell.slot_popup_texts(slot).iter().any(t => t.0 == "Chandra password dialog"))
let dir = @sys.getenv("CHANDRA_AUTH_SHOTS")
if dir != "" {
ignore(@sys.write_file_bytes(dir + "/13-settings.png", @renderer.encode_png_compressed(comp.compose_frame())))
}
comp.shell.set_session_setting(3, false)
assert_false(comp.shell.native_auth_agent)
comp.close()
}
+58 -1
View File
@@ -145,6 +145,23 @@ pub(all) struct ChandraCompositor {
mut rec_pointer : Bool mut rec_pointer : Bool
mut rec_press : Bool mut rec_press : Bool
mut last_recording : String mut last_recording : String
/// Chandra's polkit agent (auth.mbt), while it is registered; the system bus socket it uses
/// ("" finds it); the dialog while it is up; key releases it swallows; how to reach polkit's
/// helper (empty: the usual routes; tests set their own); the keymap typing goes through.
mut polkit : @polkit.PolkitAgent?
mut polkit_bus : String
mut auth : AuthUi?
auth_swallow : Array[UInt]
mut auth_routes : Array[@polkit.HelperRoute]
mut keymap : (Bytes, @polkit.Keymap)?
/// How requests are put into words (tests pass their own process lookups); None: the usual.
mut auth_describe : ((@polkit.AuthRequest) -> @polkit.Description)?
/// A third-party polkit agent was started (when ours is off or couldn't register).
mut fallback_agent_started : Bool
/// The rest of the xkb modifier state (`mods` holds the depressed modifiers).
mut mods_latched : UInt
mut mods_locked : UInt
mut mods_group : UInt
} }
///| ///|
@@ -174,6 +191,17 @@ pub fn ChandraCompositor::new(
theme, theme,
dark_theme: theme, dark_theme: theme,
sync_system_theme: false, sync_system_theme: false,
polkit: None,
polkit_bus: "",
auth: None,
auth_swallow: [],
auth_routes: [],
keymap: None,
auth_describe: None,
fallback_agent_started: false,
mods_latched: 0U,
mods_locked: 0U,
mods_group: 0U,
settings_portal: None, settings_portal: None,
control: None, control: None,
login_session: false, login_session: false,
@@ -283,6 +311,11 @@ pub fn ChandraCompositor::close(self : ChandraCompositor) -> Unit {
release_snapshot(win.surface) release_snapshot(win.surface)
} }
self.stop_control() self.stop_control()
self.close_auth(Some(Err("The session is ending")))
match self.polkit {
Some(a) => a.stop()
None => ()
}
self.shell.shutdown() self.shell.shutdown()
match self.settings_portal { match self.settings_portal {
Some(p) => p.close() Some(p) => p.close()
@@ -389,6 +422,7 @@ fn ChandraCompositor::flush_configures(self : ChandraCompositor) -> Unit {
pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit { pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit {
self.flush_configures() self.flush_configures()
self.portal_tick() self.portal_tick()
self.auth_tick()
self.control_tick() self.control_tick()
let events = self.server.poll_events() let events = self.server.poll_events()
for ev in events { for ev in events {
@@ -598,6 +632,7 @@ pub fn ChandraCompositor::has_timed_work(self : ChandraCompositor) -> Bool {
self.shot_request is Some(_) || self.shot_request is Some(_) ||
self.rec_request is Some(_) || self.rec_request is Some(_) ||
self.shot_toast is Some(_) || self.shot_toast is Some(_) ||
self.auth_animating() ||
self.thumbs_pending() || self.thumbs_pending() ||
self.shell.animating() self.shell.animating()
} }
@@ -669,7 +704,8 @@ fn ChandraCompositor::build_scene(
} }
} }
for p in self.popups { // Client menus would draw above the auth dialog: none while it is up.
for p in (if self.auth is Some(_) { [] } else { self.popups }) {
match p.surface { match p.surface {
Some(snap) => scene.popups.push((self.popup_rect(p), snap)) Some(snap) => scene.popups.push((self.popup_rect(p), snap))
None => () None => ()
@@ -729,6 +765,7 @@ fn ChandraCompositor::build_scene(
panel_ops.append(self.switcher_ops()) panel_ops.append(self.switcher_ops())
} }
panel_ops.append(self.screenshot_ops()) panel_ops.append(self.screenshot_ops())
panel_ops.append(self.auth_ops())
self.frames_built = self.frames_built + 1 self.frames_built = self.frames_built + 1
self.run_shell_actions() self.run_shell_actions()
// The wallpaper (the first ops) is cached by the renderer; the desktop card after it changes. // The wallpaper (the first ops) is cached by the renderer; the desktop card after it changes.
@@ -1201,6 +1238,7 @@ fn ChandraCompositor::run_shell_actions(self : ChandraCompositor) -> Unit {
@shell.ShellAction::FocusWindow(wid) => self.activate_task(wid) @shell.ShellAction::FocusWindow(wid) => self.activate_task(wid)
@shell.ShellAction::Logout => self.quit_requested = true @shell.ShellAction::Logout => self.quit_requested = true
@shell.ShellAction::ThemeChanged => self.apply_theme() @shell.ShellAction::ThemeChanged => self.apply_theme()
@shell.ShellAction::AuthAgentChanged => self.auth_agent_setting_changed()
@shell.ShellAction::Screenshot(code) => self.screenshot_request(code) @shell.ShellAction::Screenshot(code) => self.screenshot_request(code)
@shell.ShellAction::SystemPower(a) => self.system_power(a) @shell.ShellAction::SystemPower(a) => self.system_power(a)
@shell.ShellAction::Window(wid, cmd) => self.window_command(wid, cmd) @shell.ShellAction::Window(wid, cmd) => self.window_command(wid, cmd)
@@ -1292,6 +1330,21 @@ pub fn ChandraCompositor::handle_input(
time_ms : UInt, time_ms : UInt,
) -> Unit { ) -> Unit {
self.note_activity(@sys.monotonic_ms()) self.note_activity(@sys.monotonic_ms())
match ev {
Modifiers(dep, lat, lock, group) => {
self.mods_latched = lat
self.mods_locked = lock
self.mods_group = group
if self.auth is Some(_) {
self.mods = dep
}
}
_ => ()
}
// The authentication dialog takes all input while it is up.
if self.auth_input(ev) {
return
}
match ev { match ev {
Key(code, pressed) => { Key(code, pressed) => {
self.track_modifier_key(code, pressed) self.track_modifier_key(code, pressed)
@@ -1584,6 +1637,10 @@ pub fn ChandraCompositor::handle_input(
///| Cursor shape (wp_cursor_shape_v1 value) for the current pointer position: shell UI ///| Cursor shape (wp_cursor_shape_v1 value) for the current pointer position: shell UI
/// decides over the launcher; a client window decides inside its client area; otherwise default. /// decides over the launcher; a client window decides inside its client area; otherwise default.
pub fn ChandraCompositor::desired_cursor(self : ChandraCompositor) -> UInt { pub fn ChandraCompositor::desired_cursor(self : ChandraCompositor) -> UInt {
match self.auth {
Some(ui) => return self.auth_cursor(ui)
None => ()
}
match self.shot { match self.shot {
Some(o) => return self.overlay_cursor(o) Some(o) => return self.overlay_cursor(o)
None => () None => ()
+1 -1
View File
@@ -1701,7 +1701,7 @@ test "open_settings opens the settings module on the tab asked for" {
assert_eq(pr.h, 40 + 6 * 28 + 6) // the Wallpaper heading and the five wallpapers assert_eq(pr.h, 40 + 6 * 28 + 6) // the Wallpaper heading and the five wallpapers
assert_true(comp.shell.open_settings(Session)) assert_true(comp.shell.open_settings(Session))
ignore(comp.compose_frame()) ignore(comp.compose_frame())
assert_eq(comp.shell.slot_popup_rect(slot).h, 40 + 3 * 28 + 6) // the three settings assert_eq(comp.shell.slot_popup_rect(slot).h, 40 + 4 * 28 + 6) // the four settings
} }
///| ///|
+1
View File
@@ -13,6 +13,7 @@ import {
"chandra/desktop/compositor/gfx" @gfx, "chandra/desktop/compositor/gfx" @gfx,
"chandra/desktop/compositor/network" @network, "chandra/desktop/compositor/network" @network,
"chandra/desktop/compositor/portal" @portal, "chandra/desktop/compositor/portal" @portal,
"chandra/desktop/compositor/polkit" @polkit,
} }
supported_targets = "+native+wasm" supported_targets = "+native+wasm"
+331
View File
@@ -0,0 +1,331 @@
///| Chandra's polkit authentication agent: registers with polkitd on the system bus for this
/// login session and queues the BeginAuthentication calls it gets, which the compositor answers
/// with its own dialog.
///
/// polkitd calls org.freedesktop.PolicyKit1.AuthenticationAgent.BeginAuthentication on the
/// agent registered for the session of whoever needs authorizing (run0, pkexec, udisks, ...).
/// The call stays unanswered until the user is done: an empty reply once the helper said
/// SUCCESS (the helper itself told polkitd who authenticated), or the error
/// org.freedesktop.PolicyKit1.Error.Cancelled when they dismissed it. polkitd can withdraw a
/// request with CancelAuthentication(cookie) (the asking process went away).
///|
pub let agent_path : String = "/org/chandra/PolicyKit1/AuthenticationAgent"
///|
pub let agent_iface : String = "org.freedesktop.PolicyKit1.AuthenticationAgent"
///|
pub let authority_name : String = "org.freedesktop.PolicyKit1"
///|
pub let authority_path : String = "/org/freedesktop/PolicyKit1/Authority"
///|
pub let authority_iface : String = "org.freedesktop.PolicyKit1.Authority"
///|
pub let err_cancelled : String = "org.freedesktop.PolicyKit1.Error.Cancelled"
///|
pub let err_failed : String = "org.freedesktop.PolicyKit1.Error.Failed"
///|
let agent_introspection : String =
#|<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
#| "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
#|<node>
#| <interface name="org.freedesktop.PolicyKit1.AuthenticationAgent">
#| <method name="BeginAuthentication">
#| <arg type="s" name="action_id" direction="in"/>
#| <arg type="s" name="message" direction="in"/>
#| <arg type="s" name="icon_name" direction="in"/>
#| <arg type="a{ss}" name="details" direction="in"/>
#| <arg type="s" name="cookie" direction="in"/>
#| <arg type="a(sa{sv})" name="identities" direction="in"/>
#| </method>
#| <method name="CancelAuthentication"><arg type="s" name="cookie" direction="in"/></method>
#| </interface>
#| <interface name="org.freedesktop.DBus.Introspectable">
#| <method name="Introspect"><arg type="s" direction="out"/></method>
#| </interface>
#| <interface name="org.freedesktop.DBus.Peer"><method name="Ping"/></interface>
#|</node>
///| A request waiting for the user, with the call to answer.
pub(all) struct Pending {
req : AuthRequest
call : @network.DMessage
}
///| The agent.
pub struct PolkitAgent {
mut bus : @network.DBus?
/// The system bus socket to use; "" finds it from the environment.
bus_path : String
mut registered : Bool
/// RegisterAuthenticationAgent was sent and not answered yet.
mut registering : Bool
/// Why registering failed (or the bus went away), "" when it didn't.
mut error : String
/// The subject to register for; None: this login session.
subject : @network.DValue?
/// Requests in the order they came; the dialog shows the first.
queue : Array[Pending]
/// Turns BeginAuthentication's arguments into a request (tests swap the passwd lookup).
make_request : (Array[@network.DValue]) -> AuthRequest?
}
///|
pub fn PolkitAgent::new(
bus_path? : String = "",
subject? : @network.DValue,
make_request? : (Array[@network.DValue]) -> AuthRequest? = AuthRequest::from_args,
) -> PolkitAgent {
{ bus: None, bus_path, registered: false, registering: false, error: "", subject, queue: [], make_request }
}
///| The subject the agent registers for: this login session (XDG_SESSION_ID, else logind's
/// session of our pid).
fn session_subject(bus : @network.DBus) -> @network.DValue? {
let mut id = @sys.getenv("XDG_SESSION_ID")
if id == "" {
let r = bus.call_sync(
@network.DMessage::call(
"org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "GetSessionByPID",
[U32(@sys.getpid().reinterpret_as_uint())],
),
1000,
)
match r {
Some({ mtype: 2, body: [Path(p)], .. }) => {
let g = bus.call_sync(
@network.DMessage::call(
"org.freedesktop.login1", p, "org.freedesktop.DBus.Properties", "Get",
[Str("org.freedesktop.login1.Session"), Str("Id")],
),
1000,
)
match g {
Some({ mtype: 2, body: [Variant(Str(s))], .. }) => id = s
_ => ()
}
}
_ => ()
}
}
if id == "" {
None
} else {
Some(Struct([Str("unix-session"), @network.dict("v", [("session-id", Variant(Str(id)))])]))
}
}
///| Connect to the system bus and ask polkitd to make us this session's agent. The answer
/// comes later (`tick`): `registered`, or `failed` with `error` (no polkit, or another agent
/// already has the session). False (with `error`) when there is no bus or session to ask for.
pub fn PolkitAgent::start(self : PolkitAgent) -> Bool {
if self.registered || self.registering {
return true
}
let path = if self.bus_path != "" { self.bus_path } else { @network.system_bus_path() }
let bus = match @network.DBus::open(path) {
Some(b) => b
None => {
self.error = "no system bus at " + path
return false
}
}
let subject = match self.subject {
Some(s) => s
None =>
match session_subject(bus) {
Some(s) => s
None => {
self.error = "no login session (XDG_SESSION_ID unset and logind doesn't know us)"
bus.close()
return false
}
}
}
bus.set_on_call(fn(m) { self.on_call(bus, m) })
let lang = if @sys.getenv("LANG") != "" { @sys.getenv("LANG") } else { "en_US.UTF-8" }
self.bus = Some(bus)
self.registering = true
self.error = ""
let serial = bus.call(
@network.DMessage::call(authority_name, authority_path, authority_iface, "RegisterAuthenticationAgent", [
subject,
Str(lang),
Str(agent_path),
]),
on_reply=fn(m) {
self.registering = false
if m.mtype == @network.method_return {
self.registered = true
} else {
self.error = m.error_text()
bus.close()
}
},
)
if serial == 0 {
self.registering = false
self.error = "could not reach polkit"
self.bus = None
return false
}
true
}
///| Registering failed or the agent lost the bus (see `error`).
pub fn PolkitAgent::failed(self : PolkitAgent) -> Bool {
!self.registered && !self.registering
}
///| Answer a call to the agent object.
fn PolkitAgent::on_call(self : PolkitAgent, bus : @network.DBus, m : @network.DMessage) -> Unit {
match (m.iface, m.meth) {
("org.freedesktop.DBus.Peer", "Ping") => bus.reply(m, [])
("org.freedesktop.DBus.Introspectable", "Introspect") =>
bus.reply(m, [Str(if m.path == agent_path { agent_introspection } else { "<node/>" })])
(i, "BeginAuthentication") if i == agent_iface || i == "" =>
if m.path != agent_path {
bus.reply_error(m, "org.freedesktop.DBus.Error.UnknownObject", "no object " + m.path)
} else {
match (self.make_request)(m.body) {
Some(req) =>
if req.users.length() == 0 {
bus.reply_error(m, err_failed, "No user to authenticate as")
} else {
self.queue.push({ req, call: m })
}
None => bus.reply_error(m, "org.freedesktop.DBus.Error.InvalidArgs", "bad arguments")
}
}
(i, "CancelAuthentication") if i == agent_iface || i == "" =>
match m.body {
[Str(cookie)] => {
self.finish(cookie, Err("Authentication was cancelled"))
bus.reply(m, [])
}
_ => bus.reply_error(m, "org.freedesktop.DBus.Error.InvalidArgs", "bad arguments")
}
_ => bus.reply_error(m, "org.freedesktop.DBus.Error.UnknownMethod", "unknown method " + m.iface + "." + m.meth)
}
}
///| Serve calls that arrived. False once the bus went away (polkitd forgets the agent then).
pub fn PolkitAgent::tick(self : PolkitAgent) -> Bool {
match self.bus {
Some(b) => {
b.pump()
if !b.alive {
self.bus = None
self.registered = false
self.registering = false
self.queue.clear()
if self.error == "" {
self.error = "the system bus went away"
}
return false
}
true
}
None => false
}
}
///| The request to show, if any.
pub fn PolkitAgent::current(self : PolkitAgent) -> AuthRequest? {
self.queue.get(0).map(p => p.req)
}
///| Whether request `cookie` is still waiting (polkitd may have cancelled it).
pub fn PolkitAgent::waiting(self : PolkitAgent, cookie : String) -> Bool {
self.queue.iter().any(p => p.req.cookie == cookie)
}
///| Answer request `cookie`: Ok once authorized, Err(message) when it was dismissed.
pub fn PolkitAgent::finish(self : PolkitAgent, cookie : String, result : Result[Unit, String]) -> Unit {
match self.queue.search_by(p => p.req.cookie == cookie) {
Some(i) => {
let p = self.queue.remove(i)
match self.bus {
Some(b) =>
match result {
Ok(_) => b.reply(p.call, [])
Err(text) => b.reply_error(p.call, err_cancelled, text)
}
None => ()
}
}
None => ()
}
}
///| The bus socket, for the main loop to wake on (-1 when not connected).
pub fn PolkitAgent::fd(self : PolkitAgent) -> Int {
match self.bus {
Some(b) => b.fd()
None => -1
}
}
///| Whether polkitd has us as the session's agent.
pub fn PolkitAgent::registered(self : PolkitAgent) -> Bool {
self.registered
}
///| Why the last start failed ("" when it didn't).
pub fn PolkitAgent::error(self : PolkitAgent) -> String {
self.error
}
///| Stop being the agent: dismiss what waits, unregister, leave the bus.
pub fn PolkitAgent::stop(self : PolkitAgent) -> Unit {
let cookies = self.queue.map(p => p.req.cookie)
for c in cookies {
self.finish(c, Err("The authentication agent stopped"))
}
match self.bus {
Some(b) => {
match (match self.subject { Some(s) => Some(s); None => session_subject(b) }) {
Some(subject) =>
ignore(
b.call_sync(
@network.DMessage::call(authority_name, authority_path, authority_iface, "UnregisterAuthenticationAgent", [
subject,
Str(agent_path),
]),
1000,
),
)
None => ()
}
b.close()
}
None => ()
}
self.bus = None
self.registered = false
self.registering = false
}
///| Ways to reach the helper, to try in order: polkit 126's socket (when
/// polkit-agent-helper.socket is enabled; connecting fails otherwise), then the setuid program.
/// CHANDRA_POLKIT_HELPER names one instead (`socket:/path` or a program path).
pub fn helper_routes() -> Array[HelperRoute] {
let h = @sys.getenv("CHANDRA_POLKIT_HELPER")
if h != "" {
return [if h.has_prefix("socket:") { Socket(h[7:].to_string()) } else { Program(h) }]
}
let out : Array[HelperRoute] = [Socket(helper_socket)]
for p in helper_paths {
if @sys.has_exe(p) {
out.push(Program(p))
break
}
}
out
}
+248
View File
@@ -0,0 +1,248 @@
///| Turning a request into words: what is asked, for which command, by whom.
///
/// polkit's own message for run0 is "Authentication is required to start transient unit
/// 'run-p15802-i1990.service'.": true, but it says nothing a person can judge. run0 asks
/// systemd for a transient unit, systemd asks polkit, and polkit tells us run0's pid (the
/// subject, `polkit.subject-pid`; the unit name `run-p<pid>-i<n>.service` carries it too). From
/// run0's command line we can show what it will run. pkexec puts the command in the details.
///| A process's command line (NUL-separated /proc/<pid>/cmdline), empty when it is gone.
pub fn proc_cmdline(pid : Int) -> Array[String] {
if pid <= 0 {
return []
}
split_cmdline(@sys.read_proc_bytes("/proc/" + pid.to_string() + "/cmdline"))
}
///| Split NUL-separated arguments.
pub fn split_cmdline(b : Bytes) -> Array[String] {
let out : Array[String] = []
let cur : Array[Byte] = []
for i = 0; i < b.length(); i = i + 1 {
if b[i] == b'\x00' {
out.push(@utf8.decode_lossy(Bytes::from_array(cur)))
cur.clear()
} else {
cur.push(b[i])
}
}
if cur.length() > 0 {
out.push(@utf8.decode_lossy(Bytes::from_array(cur)))
}
out
}
///| A process's name (/proc/<pid>/comm) and parent pid (/proc/<pid>/stat field 4).
pub fn proc_name_parent(pid : Int) -> (String, Int) {
if pid <= 0 {
return ("", 0)
}
let comm = @utf8.decode_lossy(@sys.read_proc_bytes("/proc/" + pid.to_string() + "/comm")).trim(chars="\n ").to_string()
let stat = @utf8.decode_lossy(@sys.read_proc_bytes("/proc/" + pid.to_string() + "/stat"))
// "pid (comm) S ppid ...": the name can hold spaces and parentheses, so read after the last ')'.
let ppid = match stat.rev_find(")") {
Some(i) => {
let rest = stat[i + 1:].to_string().trim(chars=" ").to_string().split(" ").to_array()
if rest.length() >= 2 {
parse_uint(rest[1].to_string()).unwrap_or(0)
} else {
0
}
}
None => 0
}
(comm, ppid)
}
///| The last part of a path.
pub fn basename(p : String) -> String {
match p.rev_find("/") {
Some(i) => p[i + 1:].to_string()
None => p
}
}
///| `run0`'s options that take a separate value (`-u root`, `--setenv FOO=1`).
let run0_value_opts : Array[String] = [
"-u", "--user", "-g", "--group", "-D", "--chdir", "--setenv", "-p", "--property", "--description",
"--slice", "--unit", "--nice", "--machine", "--background", "--shell-prompt-prefix", "--area",
]
///| What a `run0` (or `systemd-run`) command line runs: (target user, the command's arguments).
/// The user is "root" unless -u/--user says otherwise; no arguments means a login shell.
pub fn parse_run0(argv : Array[String]) -> (String, Array[String]) {
let mut user = "root"
let mut i = 1
while i < argv.length() {
let a = argv[i]
if a == "--" {
i = i + 1
break
}
if !a.has_prefix("-") || a == "-" {
break
}
if a.has_prefix("--user=") {
user = a[7:].to_string()
} else if a.has_prefix("-u") && a.length() > 2 {
user = a[2:].to_string()
} else if run0_value_opts.contains(a) {
if (a == "-u" || a == "--user") && i + 1 < argv.length() {
user = argv[i + 1]
}
i = i + 1
}
i = i + 1
}
let cmd : Array[String] = []
while i < argv.length() {
cmd.push(argv[i])
i = i + 1
}
(user, cmd)
}
///| An argument as a shell would need it written: bare when safe, else in single quotes.
pub fn shell_quote(a : String) -> String {
if a == "" {
return "''"
}
let mut safe = true
for c in a {
if !(c.is_ascii_alphabetic() || c.is_ascii_digit() || "-_./=:,+@%".contains_char(c)) {
safe = false
break
}
}
if safe {
a
} else {
"'" + a.replace_all(old="'", new="'\\''") + "'"
}
}
///| A command line for display.
pub fn command_text(argv : Array[String]) -> String {
argv.map(shell_quote).join(" ")
}
///| The pid in a run0 unit name `run-p<pid>-i<n>.service` (or `run-u<n>.service`: none).
pub fn run0_unit_pid(unit : String) -> Int? {
if !unit.has_prefix("run-p") {
return None
}
let rest = unit[5:].to_string()
match rest.find("-") {
Some(i) => parse_uint(rest[:i].to_string())
None => None
}
}
///| The quoted name in a message like "... transient unit 'run-p15802-i1990.service'.".
pub fn quoted_in(message : String) -> String {
match message.find("'") {
Some(a) => {
let rest = message[a + 1:].to_string()
match rest.find("'") {
Some(b) => rest[:b].to_string()
None => ""
}
}
None => ""
}
}
///| How the dialog presents a request.
pub(all) struct Description {
/// The headline ("Run a command as root", or polkit's message for other actions).
title : String
/// One line under it: what allowing does.
subtitle : String
/// The command that will run, written as a shell would ("" when it isn't a command).
command : String
/// The command's program name (for its app icon), "" when none.
program : String
/// Label/value rows for the Details section.
details : Array[(String, String)]
}
///| Who asked: the subject process, then its parent ("run0 (pid 15802) from bash").
fn requester(pid : Int) -> String {
if pid <= 0 {
return ""
}
let (name, ppid) = proc_name_parent(pid)
if name == "" {
return "pid " + pid.to_string()
}
let (pname, _) = proc_name_parent(ppid)
name + " (pid " + pid.to_string() + ")" + (if pname != "" && ppid > 1 { ", started from " + pname } else { "" })
}
///| Words for `req`. `cmdline` reads a process's arguments (tests pass their own).
pub fn describe(req : AuthRequest, cmdline? : (Int) -> Array[String] = proc_cmdline, who? : (Int) -> String = requester) -> Description {
let subject = parse_uint(req.detail("polkit.subject-pid")).unwrap_or(0)
let caller = parse_uint(req.detail("polkit.caller-pid")).unwrap_or(0)
let unit = if req.detail("unit") != "" { req.detail("unit") } else { quoted_in(req.message) }
let details : Array[(String, String)] = []
let add = fn(k : String, v : String) { if v != "" { details.push((k, v)) } }
// run0 / systemd-run: a transient unit for a process we can read.
let run0_pid = if req.action_id == "org.freedesktop.systemd1.manage-units" {
match run0_unit_pid(unit) {
Some(p) => p
None => if unit.has_prefix("run-") { subject } else { 0 }
}
} else {
0
}
let run0_argv = if run0_pid > 0 {
let a = cmdline(if subject > 0 { subject } else { run0_pid })
if a.length() > 0 { a } else { cmdline(run0_pid) }
} else {
[]
}
let tool = if run0_argv.length() > 0 { basename(run0_argv[0]) } else { "" }
if tool == "run0" || tool == "systemd-run" {
let (user, cmd) = parse_run0(run0_argv)
let target = if user == "root" { "root" } else { user }
let shell = cmd.length() == 0
add("Requested by", who(if subject > 0 { subject } else { run0_pid }))
add("Runs as", target)
add("Unit", unit)
add("Action", req.action_id)
return {
title: if shell { "Open a shell as " + target } else { "Run a command as " + target },
subtitle: tool + " needs your password to " + (if shell { "start a " + target + " shell." } else { "run this as " + target + ":" }),
command: command_text(cmd),
program: if shell { "" } else { basename(cmd[0]) },
details,
}
}
// pkexec: the details carry the command.
if req.action_id == "org.freedesktop.policykit.exec" || req.detail("command_line") != "" {
let user = if req.detail("user") != "" { req.detail("user") } else { "root" }
let line = req.detail("command_line")
let program = basename(if req.detail("program") != "" { req.detail("program") } else { line.split(" ").to_array().get(0).map(v => v.to_string()).unwrap_or("") })
add("Requested by", who(if subject > 0 { subject } else { caller }))
add("Runs as", user)
add("Action", req.action_id)
return {
title: "Run a program as " + user,
subtitle: "pkexec needs your password to run this as " + user + ":",
command: line,
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"))
add("Action", req.action_id)
{
title: if req.message != "" { req.message } else { "Authentication required" },
subtitle: "An app wants permission for a system action. Enter your password to allow it.",
command: "",
program: "",
details,
}
}
+425
View File
@@ -0,0 +1,425 @@
///| The authentication dialog's state, apart from how it is drawn: what PAM asked, what was
/// typed (kept as characters so it can be wiped), which control has the keyboard, the last
/// error. The compositor draws it (compositor/host/auth.mbt) and runs the helper.
///| Where the conversation is.
pub(all) enum Phase {
/// The helper was started and hasn't asked anything yet.
Starting
/// PAM asked for an answer (`prompt`); the field takes typing.
Prompt
/// The answer went to PAM; waiting for the verdict.
Checking
/// PAM only said something (say "Place your finger on the reader") and waits on its own.
Waiting
} derive(Eq, Debug)
///| The dialog's controls, in Tab order.
pub(all) enum Focus {
Field
User
Reveal
Details
Cancel
Allow
} derive(Eq, Debug)
///| What the compositor has to do after an event.
pub(all) enum DialogEffect {
Nothing
/// Send these bytes to the helper as the answer (then zero them).
Answer(FixedArray[Byte])
/// Run the helper again (another user picked, or the last attempt failed).
Restart
/// The user dismissed the dialog.
Cancelled
/// The helper said SUCCESS.
Authorized
}
///| Evdev key codes the dialog knows.
pub let key_esc : UInt = 1
///|
pub let key_backspace : UInt = 14
///|
pub let key_tab : UInt = 15
///|
pub let key_enter : UInt = 28
///|
pub let key_kp_enter : UInt = 96
///|
pub let key_space : UInt = 57
///|
pub let key_left : UInt = 105
///|
pub let key_right : UInt = 106
///|
pub let key_up : UInt = 103
///|
pub let key_down : UInt = 108
///|
pub let key_u : UInt = 22
///|
pub let key_d : UInt = 32
///|
pub let key_r : UInt = 19
///| The dialog for one request.
pub(all) struct AuthDialog {
req : AuthRequest
desc : Description
mut user_sel : Int
mut phase : Phase
/// PAM's prompt, tidied ("Password: " -> "Password").
mut prompt : String
/// The prompt's answer is shown as typed (PAM_PROMPT_ECHO_ON).
mut echo : Bool
input : Array[Char]
/// Show the password instead of dots.
mut reveal : Bool
mut caps : Bool
/// The last error (PAM's message, or ours after a failed attempt); "" when none.
mut error : String
/// PAM's last information message.
mut info : String
mut details_open : Bool
mut failures : Int
/// When the last failure shook the card (monotonic ms), 0 for never.
mut shake_at : UInt64
mut focus : Focus
/// Enter came before PAM's prompt: answer as soon as it does.
mut submit_queued : Bool
}
///|
pub fn AuthDialog::new(req : AuthRequest, desc : Description) -> AuthDialog {
{
req,
desc,
user_sel: 0,
phase: Starting,
prompt: "Password",
echo: false,
input: [],
reveal: false,
caps: false,
error: if req.users.length() == 0 { "No account can approve this here." } else { "" },
info: "",
details_open: false,
failures: 0,
shake_at: 0UL,
focus: Field,
submit_queued: false,
}
}
///| The user answering, if any.
pub fn AuthDialog::user(self : AuthDialog) -> AuthUser? {
self.req.users.get(self.user_sel)
}
///| "Password: " -> "Password"; "Password for nandi: " stays readable.
pub fn tidy_prompt(p : String) -> String {
let t = p.trim(chars=" \t\n").to_string()
let t = if t.has_suffix(":") { t[:t.length() - 1].to_string().trim(chars=" ").to_string() } else { t }
if t == "" { "Password" } else { t }
}
///| Wipe what was typed.
pub fn AuthDialog::wipe(self : AuthDialog) -> Unit {
for i = 0; i < self.input.length(); i = i + 1 {
self.input[i] = '\u{0}'
}
self.input.clear()
}
///| What was typed, as UTF-8 bytes in a buffer the caller zeroes after use; the field is wiped.
fn AuthDialog::take_answer(self : AuthDialog) -> FixedArray[Byte] {
let n = self.input.fold(init=0, fn(acc, c) {
let v = c.to_int()
acc + (if v < 0x80 { 1 } else if v < 0x800 { 2 } else if v < 0x10000 { 3 } else { 4 })
})
let out : FixedArray[Byte] = FixedArray::make(n, b'\x00')
let mut k = 0
for c in self.input {
let v = c.to_int()
if v < 0x80 {
out[k] = v.to_byte()
k = k + 1
} else if v < 0x800 {
out[k] = (0xC0 | (v >> 6)).to_byte()
out[k + 1] = (0x80 | (v & 0x3F)).to_byte()
k = k + 2
} else if v < 0x10000 {
out[k] = (0xE0 | (v >> 12)).to_byte()
out[k + 1] = (0x80 | ((v >> 6) & 0x3F)).to_byte()
out[k + 2] = (0x80 | (v & 0x3F)).to_byte()
k = k + 3
} else {
out[k] = (0xF0 | (v >> 18)).to_byte()
out[k + 1] = (0x80 | ((v >> 12) & 0x3F)).to_byte()
out[k + 2] = (0x80 | ((v >> 6) & 0x3F)).to_byte()
out[k + 3] = (0x80 | (v & 0x3F)).to_byte()
k = k + 4
}
}
self.wipe()
out
}
///| Zero a buffer an answer was in.
pub fn zero(b : FixedArray[Byte]) -> Unit {
for i = 0; i < b.length(); i = i + 1 {
b[i] = b'\x00'
}
}
///| Send what was typed, if PAM is asking; else remember to once it does.
fn AuthDialog::submit(self : AuthDialog) -> DialogEffect {
match self.phase {
Prompt =>
if self.input.length() == 0 && !self.echo {
Nothing
} else {
self.phase = Checking
self.error = ""
Answer(self.take_answer())
}
Starting | Waiting => {
self.submit_queued = self.input.length() > 0
Nothing
}
Checking => Nothing
}
}
///| Something from the helper. `now` is the monotonic clock (for the shake).
pub fn AuthDialog::helper(self : AuthDialog, ev : HelperEvent, now : UInt64) -> DialogEffect {
match ev {
PromptEchoOff(p) | PromptEchoOn(p) => {
self.phase = Prompt
self.prompt = tidy_prompt(p)
self.echo = ev is PromptEchoOn(_)
self.info = ""
if self.submit_queued {
self.submit_queued = false
return self.submit()
}
Nothing
}
ErrorMsg(m) => {
self.error = m.trim(chars=" \n").to_string()
Nothing
}
TextInfo(m) => {
self.info = m.trim(chars=" \n").to_string()
if self.phase == Starting {
self.phase = Waiting
}
Nothing
}
Success => Authorized
Failure => {
self.failures = self.failures + 1
self.shake_at = if now == 0UL { 1UL } else { now }
if self.error == "" {
self.error = if self.echo {
"That didn't work. Try again."
} else {
"Wrong password. Try again."
}
}
self.wipe()
self.submit_queued = false
self.phase = Starting
self.info = ""
self.focus = Field
Restart
}
}
}
///| The controls Tab moves through, in order (the user picker only with several users).
pub fn AuthDialog::focus_order(self : AuthDialog) -> Array[Focus] {
let out : Array[Focus] = [Field]
if self.req.users.length() > 1 {
out.push(User)
}
out.push(Reveal)
out.push(Details)
out.push(Cancel)
out.push(Allow)
out
}
///| Move the keyboard focus by `delta` along the Tab order.
fn AuthDialog::move_focus(self : AuthDialog, delta : Int) -> Unit {
let order = self.focus_order()
let i = order.search(self.focus).unwrap_or(0)
let n = order.length()
self.focus = order[((i + delta) % n + n) % n]
}
///| Pick the user `delta` away (wrapping). Restart when it changed.
fn AuthDialog::cycle_user(self : AuthDialog, delta : Int) -> DialogEffect {
let n = self.req.users.length()
if n < 2 {
return Nothing
}
self.user_sel = ((self.user_sel + delta) % n + n) % n
self.wipe()
self.error = ""
self.info = ""
self.phase = Starting
self.submit_queued = false
Restart
}
///| Activate control `f` (Enter or Space on it, or a click).
pub fn AuthDialog::activate(self : AuthDialog, f : Focus) -> DialogEffect {
match f {
Field => {
self.focus = Field
Nothing
}
User => {
self.focus = User
self.cycle_user(1)
}
Reveal => {
self.focus = Reveal
self.reveal = !self.reveal
Nothing
}
Details => {
self.focus = Details
self.details_open = !self.details_open
Nothing
}
Cancel => Cancelled
Allow => self.submit()
}
}
///| A key press: `code` (evdev), the modifier state (Shift, Ctrl, Alt bits), and the character it
/// types on the current layout, if any.
pub fn AuthDialog::key(self : AuthDialog, code : UInt, mods : UInt, ch : Char?) -> DialogEffect {
let ctrl = (mods & mask_ctrl) != 0U
let shift = (mods & mask_shift) != 0U
let alt = (mods & mask_alt) != 0U
if code == key_esc {
return Cancelled
}
if code == key_tab {
self.move_focus(if shift { -1 } else { 1 })
return Nothing
}
if code == key_enter || code == key_kp_enter {
return match self.focus {
Field | Allow => self.submit()
other => self.activate(other)
}
}
// Alt+D details, Alt+R reveal: reachable from the field without leaving it.
if alt && code == key_d {
self.details_open = !self.details_open
return Nothing
}
if alt && code == key_r {
self.reveal = !self.reveal
return Nothing
}
if self.focus == User && (code == key_left || code == key_up) {
return self.cycle_user(-1)
}
if self.focus == User && (code == key_right || code == key_down) {
return self.cycle_user(1)
}
if code == key_space && self.focus != Field {
return self.activate(self.focus)
}
if self.phase == Checking {
return Nothing
}
if code == key_backspace || (ctrl && code == key_u) {
if ctrl {
self.wipe()
} else if self.input.length() > 0 {
let last = self.input.length() - 1
self.input[last] = '\u{0}'
ignore(self.input.pop())
}
self.focus = Field
return Nothing
}
if ctrl || alt {
return Nothing
}
match ch {
Some(c) => {
if self.input.length() < 512 {
self.input.push(c)
}
self.focus = Field
// Typing again after an error clears it.
if self.failures > 0 {
self.error = ""
}
Nothing
}
None => Nothing
}
}
///| Horizontal offset of the card while it shakes after a failure (0 when still).
pub fn AuthDialog::shake_offset(self : AuthDialog, now : UInt64) -> Int {
if self.shake_at == 0UL || now < self.shake_at {
return 0
}
let t = (now - self.shake_at).to_int()
let dur = 420
if t >= dur {
return 0
}
// Three swings, fading out.
let period = dur / 6
let phase = t % period
let tri = if phase < period / 2 { phase * 4 - period } else { 3 * period - phase * 4 }
let amp = 12 * (dur - t) / dur
tri * amp / period
}
///| Whether the card is still shaking.
pub fn AuthDialog::shaking(self : AuthDialog, now : UInt64) -> Bool {
self.shake_at != 0UL && now >= self.shake_at && now - self.shake_at < 420UL
}
///| The field's text as shown: the answer (echo or revealed) or one dot per character.
pub fn AuthDialog::field_text(self : AuthDialog) -> String {
if self.echo || self.reveal {
String::from_array(self.input)
} else {
let sb = StringBuilder::new()
for _ in self.input {
sb.write_char('●')
}
sb.to_string()
}
}
///| The number of characters typed.
pub fn AuthDialog::typed(self : AuthDialog) -> Int {
self.input.length()
}
+227
View File
@@ -0,0 +1,227 @@
///| The PAM conversation, through polkit's helper.
///
/// polkit authenticates with `polkit-agent-helper-1` (part of polkit, run as root). An agent
/// talks to it one line at a time: the helper writes what PAM asks or says,
/// PAM_PROMPT_ECHO_OFF <prompt> (a password: answer with one line)
/// PAM_PROMPT_ECHO_ON <prompt> (a visible answer, say a user name or a one-time code)
/// PAM_ERROR_MSG <text> / PAM_TEXT_INFO <text> (messages, no answer)
/// SUCCESS / FAILURE (the end; on success the helper has told polkitd itself)
/// with the text escaped as g_strescape does. There are two ways to start it:
/// - polkit 126+ (systemd): connect to /run/polkit/agent-helper.socket and send the user name and
/// the cookie, one line each (socket activation; no setuid binary).
/// - otherwise run the setuid helper with the user name as its argument and send the cookie.
///| What the helper said.
pub(all) enum HelperEvent {
PromptEchoOff(String)
PromptEchoOn(String)
ErrorMsg(String)
TextInfo(String)
Success
Failure
} derive(Eq, Debug)
///| Undo g_strescape: \n \t \r \b \f \v \\ \" and octal \NNN (bytes, re-read as UTF-8).
pub fn unescape(s : String) -> String {
let out : Array[Byte] = []
let cs = chars_of(s)
let push_char = fn(c : Char) {
let b = @utf8.encode(c.to_string())
for i = 0; i < b.length(); i = i + 1 {
out.push(b[i])
}
}
let mut i = 0
while i < cs.length() {
let c = cs[i]
if c != '\\' || i + 1 >= cs.length() {
push_char(c)
i = i + 1
continue
}
let d = cs[i + 1]
if d >= '0' && d <= '7' {
let mut v = 0
let mut k = 0
while k < 3 && i + 1 + k < cs.length() && cs[i + 1 + k] >= '0' && cs[i + 1 + k] <= '7' {
v = v * 8 + (cs[i + 1 + k].to_int() - '0'.to_int())
k = k + 1
}
out.push((v & 0xff).to_byte())
i = i + 1 + k
continue
}
let r = match d {
'n' => '\n'
't' => '\t'
'r' => '\r'
'b' => '\b'
'f' => '\u{0c}'
'v' => '\u{0b}'
_ => d
}
push_char(r)
i = i + 2
}
@utf8.decode_lossy(Bytes::from_array(out))
}
///| Parse one line from the helper (without its newline). None for lines we don't know.
pub fn parse_helper_line(line : String) -> HelperEvent? {
let after = fn(p : String) { unescape(line[p.length():].to_string()) }
if line.has_prefix("PAM_PROMPT_ECHO_OFF ") {
Some(PromptEchoOff(after("PAM_PROMPT_ECHO_OFF ")))
} else if line.has_prefix("PAM_PROMPT_ECHO_ON ") {
Some(PromptEchoOn(after("PAM_PROMPT_ECHO_ON ")))
} else if line.has_prefix("PAM_ERROR_MSG ") {
Some(ErrorMsg(after("PAM_ERROR_MSG ")))
} else if line.has_prefix("PAM_TEXT_INFO ") {
Some(TextInfo(after("PAM_TEXT_INFO ")))
} else if line.has_prefix("SUCCESS") {
Some(Success)
} else if line.has_prefix("FAILURE") {
Some(Failure)
} else {
None
}
}
///| Where polkit installs the setuid helper, by distribution.
pub let helper_paths : Array[String] = [
"/usr/lib/polkit-1/polkit-agent-helper-1", "/usr/libexec/polkit-agent-helper-1", "/usr/libexec/polkit-1/polkit-agent-helper-1",
"/usr/lib/policykit-1/polkit-agent-helper-1",
]
///| The socket-activated helper (polkit 126+).
pub let helper_socket : String = "/run/polkit/agent-helper.socket"
///| How to reach the helper: a socket to connect to, or a program to run on a socket pair.
pub(all) enum HelperRoute {
Socket(String)
Program(String)
} derive(Eq, Debug)
///| One run of the helper: the connection and the bytes read but not yet a whole line.
pub struct HelperSession {
mut fd : Int
inbuf : Array[Byte]
/// Set once SUCCESS or FAILURE came, or the helper went away.
mut ended : Bool
}
///| Start the helper to authenticate `user` for `cookie` by the first route that works. None
/// when none does.
pub fn HelperSession::start_any(routes : Array[HelperRoute], user : String, cookie : String) -> HelperSession? {
for r in routes {
match HelperSession::start(r, user, cookie) {
Some(s) => return Some(s)
None => ()
}
}
None
}
///| Start the helper to authenticate `user` for `cookie`. None when it can't be started.
pub fn HelperSession::start(route : HelperRoute, user : String, cookie : String) -> HelperSession? {
let (fd, first) = match route {
Socket(path) => (@sys.unix_connect(path), user + "\n" + cookie + "\n")
Program(path) => (@sys.spawn_socket([path, user]), cookie + "\n")
}
if fd < 0 {
return None
}
let b = @utf8.encode(first)
if @sys.sendmsg_fd(fd, b, -1) != b.length() {
@sys.close_fd(fd)
return None
}
Some({ fd, inbuf: [], ended: false })
}
///| A session over an already-connected fd (tests).
pub fn HelperSession::over(fd : Int) -> HelperSession {
{ fd, inbuf: [], ended: false }
}
///| What arrived since the last call (non-blocking). The helper going away without an answer
/// reads as Failure.
pub fn HelperSession::read(self : HelperSession) -> Array[HelperEvent] {
let out : Array[HelperEvent] = []
if self.fd < 0 {
return out
}
let buf : FixedArray[Byte] = FixedArray::make(4096, b'\x00')
let mut eof = false
while @sys.poll_read(self.fd, 0) > 0 {
let (n, extra) = @sys.recvmsg_fd(self.fd, buf, buf.length())
if extra >= 0 {
@sys.close_fd(extra)
}
if n == -1 {
break
}
if n <= 0 {
eof = true
break
}
for i = 0; i < n; i = i + 1 {
self.inbuf.push(buf[i])
}
}
while true {
let mut nl = -1
for i, b in self.inbuf {
if b == b'\n' {
nl = i
break
}
}
if nl < 0 {
break
}
let line = @utf8.decode_lossy(Bytes::from_array(self.inbuf[:nl].to_array()))
let rest = self.inbuf[nl + 1:].to_array()
self.inbuf.clear()
self.inbuf.append(rest)
match parse_helper_line(line) {
Some(ev) => {
out.push(ev)
if ev == Success || ev == Failure {
self.ended = true
}
}
None => ()
}
}
if eof {
if !self.ended {
out.push(Failure)
self.ended = true
}
self.close()
}
out
}
///| Answer the prompt with `answer` (its bytes then a newline); the caller zeroes its copy.
pub fn HelperSession::respond(self : HelperSession, answer : FixedArray[Byte]) -> Bool {
if self.fd < 0 {
return false
}
let n = answer.length()
let b = Bytes::makei(n + 1, i => if i < n { answer[i] } else { b'\n' })
@sys.sendmsg_fd(self.fd, b, -1) == b.length()
}
///| The connection, for the main loop to wait on (-1 once closed).
pub fn HelperSession::fd(self : HelperSession) -> Int {
self.fd
}
///| Stop: closing the connection ends the helper's PAM conversation.
pub fn HelperSession::close(self : HelperSession) -> Unit {
if self.fd >= 0 {
@sys.close_fd(self.fd)
self.fd = -1
}
}
+634
View File
@@ -0,0 +1,634 @@
///| Characters for the password field, from the keymap clients are sent.
///
/// The compositor sees keys as evdev codes; the characters they type depend on the keyboard
/// layout, and a password typed on the wrong layout is the wrong password. So the auth dialog reads
/// the xkb keymap (text format v1, what the host hands `WaylandServer::set_keymap`): the keycode
/// names (`<AE01> = 10;`) and each key's symbols per group and level (`key <AE01> { [ 1, exclam ] };`),
/// and maps keysym names to characters (ASCII and Latin-1 names, `Uxxxx`, `0x100xxxxx`). Without a
/// keymap (nested windows, tests) a built-in US layout is used.
///| One key's keysym names: groups, then levels.
struct KeySyms {
groups : Array[Array[String]]
}
///| Characters per keycode (evdev code + 8), parsed from an xkb keymap.
pub struct Keymap {
keys : Map[Int, KeySyms]
}
///|
fn chars_of(s : String) -> Array[Char] {
let out : Array[Char] = []
for c in s {
out.push(c)
}
out
}
///|
fn str_of(cs : Array[Char], from : Int, to : Int) -> String {
let sb = StringBuilder::new()
for i = from; i < to && i < cs.length(); i = i + 1 {
sb.write_char(cs[i])
}
sb.to_string()
}
///|
fn is_space(c : Char) -> Bool {
c == ' ' || c == '\t' || c == '\n' || c == '\r'
}
///| The text of section `name` (say "xkb_symbols"): from its opening brace to the matching close.
fn section(cs : Array[Char], name : String) -> (Int, Int)? {
let n = chars_of(name)
let mut i = 0
while i + n.length() <= cs.length() {
let mut hit = true
for k = 0; k < n.length(); k = k + 1 {
if cs[i + k] != n[k] {
hit = false
break
}
}
if hit {
let mut j = i + n.length()
while j < cs.length() && cs[j] != '{' {
j = j + 1
}
let start = j + 1
let mut depth = 1
j = start
while j < cs.length() && depth > 0 {
if cs[j] == '{' {
depth = depth + 1
} else if cs[j] == '}' {
depth = depth - 1
}
j = j + 1
}
return Some((start, j - 1))
}
i = i + 1
}
None
}
///| Statements of a section body split on top-level ';' (braces nest).
fn statements(cs : Array[Char], from : Int, to : Int) -> Array[String] {
let out : Array[String] = []
let mut depth = 0
let mut start = from
let mut in_str = false
for i = from; i < to; i = i + 1 {
let c = cs[i]
if c == '"' {
in_str = !in_str
} else if !in_str {
if c == '{' {
depth = depth + 1
} else if c == '}' {
depth = depth - 1
} else if c == ';' && depth == 0 {
out.push(str_of(cs, start, i).trim(chars=" \t\r\n").to_string())
start = i + 1
}
}
}
out
}
///| `<NAME> = 10` -> ("NAME", 10); `alias <A> = <B>` handled by the caller.
fn parse_keycode(st : String) -> (String, Int)? {
if !st.has_prefix("<") {
return None
}
let cs = chars_of(st)
let mut close = -1
for i, c in cs {
if c == '>' {
close = i
break
}
}
if close < 0 {
return None
}
let name = str_of(cs, 1, close)
let rest = str_of(cs, close + 1, cs.length()).trim(chars=" \t=").to_string()
let mut v = 0
let mut any = false
for c in rest {
if c >= '0' && c <= '9' {
v = v * 10 + (c.to_int() - '0'.to_int())
any = true
} else {
break
}
}
if any {
Some((name, v))
} else {
None
}
}
///| The keysym lists in a key body: `[ a, A ]` (group 1) or `symbols[1]= [ a, A ], symbols[2]= [...]`.
fn key_groups(body : Array[Char]) -> Array[Array[String]] {
let groups : Array[Array[String]] = []
let mut i = 0
let n = body.length()
// Whether the next '[' opens a keysym list: after '{', ',' or '=' preceded by symbols[..].
let mut prev_word = ""
let word = StringBuilder::new()
let mut last_sig = '{'
while i < n {
let c = body[i]
if c == '"' {
i = i + 1
while i < n && body[i] != '"' {
i = i + 1
}
i = i + 1
last_sig = '"'
continue
}
if c.is_ascii_alphabetic() || c.is_ascii_digit() || c == '_' {
word.write_char(c)
i = i + 1
continue
}
if word.to_string() != "" {
prev_word = word.to_string()
word.reset()
last_sig = 'w'
}
if is_space(c) {
i = i + 1
continue
}
if c == '[' {
if last_sig == 'w' {
// An index like symbols[1] or actions[Group2]: skip it, remember what it indexes.
let kind = prev_word
while i < n && body[i] != ']' {
i = i + 1
}
i = i + 1
last_sig = if kind == "symbols" { 's' } else { 'x' }
continue
}
let take = last_sig == '{' || last_sig == ',' || last_sig == 'S'
let start = i + 1
while i < n && body[i] != ']' {
i = i + 1
}
if take {
let syms : Array[String] = []
for p in str_of(body, start, i).split(",") {
syms.push(p.trim(chars=" \t\r\n").to_string())
}
groups.push(syms)
}
i = i + 1
last_sig = ']'
continue
}
if c == '=' {
last_sig = if last_sig == 's' { 'S' } else { '=' }
} else if c == ',' {
last_sig = if last_sig == ']' { ',' } else { ',' }
} else {
last_sig = c
}
i = i + 1
}
groups
}
///| Parse an xkb text keymap. None when it has no symbols we can use.
pub fn Keymap::parse(text : String) -> Keymap? {
let cs = chars_of(text)
let codes : Map[String, Int] = {}
match section(cs, "xkb_keycodes") {
Some((a, b)) => {
let aliases : Array[(String, String)] = []
for st in statements(cs, a, b) {
if st.has_prefix("alias") {
let parts = st.split("=").to_array()
if parts.length() == 2 {
let al = parts[0].trim(chars=" \taliasAL").to_string()
let tg = parts[1].trim(chars=" \t").to_string()
aliases.push((al.trim(chars="<>").to_string(), tg.trim(chars="<>").to_string()))
}
} else {
match parse_keycode(st) {
Some((name, v)) => codes.set(name, v)
None => ()
}
}
}
for a in aliases {
match codes.get(a.1) {
Some(v) => if !codes.contains(a.0) { codes.set(a.0, v) }
None => ()
}
}
}
None => ()
}
let keys : Map[Int, KeySyms] = {}
match section(cs, "xkb_symbols") {
Some((a, b)) =>
for st in statements(cs, a, b) {
if !st.has_prefix("key ") && !st.has_prefix("key\t") {
continue
}
let sc = chars_of(st)
let mut lt = -1
let mut gt = -1
for i, c in sc {
if c == '<' && lt < 0 {
lt = i
} else if c == '>' && lt >= 0 {
gt = i
break
}
}
if lt < 0 || gt < 0 {
continue
}
let name = str_of(sc, lt + 1, gt)
let mut ob = -1
for i = gt; i < sc.length(); i = i + 1 {
if sc[i] == '{' {
ob = i
break
}
}
if ob < 0 {
continue
}
let body = sc[ob:].to_array()
let groups = key_groups(body)
if groups.length() == 0 {
continue
}
let code = match codes.get(name) {
Some(v) => v
None => match us_codes().get(name) {
Some(v) => v
None => continue
}
}
keys.set(code, { groups, })
}
None => ()
}
if keys.length() == 0 {
None
} else {
Some({ keys, })
}
}
///| Names of keysyms 0x20..0x7e (ASCII), in order.
let ascii_names : Array[String] = [
"space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "apostrophe",
"parenleft", "parenright", "asterisk", "plus", "comma", "minus", "period", "slash", "0", "1",
"2", "3", "4", "5", "6", "7", "8", "9", "colon", "semicolon", "less", "equal", "greater",
"question", "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash",
"bracketright", "asciicircum", "underscore", "grave", "a", "b", "c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"braceleft", "bar", "braceright", "asciitilde",
]
///| Names of keysyms 0xa0..0xff (Latin-1, keysym = code point), in order.
let latin1_names : Array[String] = [
"nobreakspace", "exclamdown", "cent", "sterling", "currency", "yen", "brokenbar", "section",
"diaeresis", "copyright", "ordfeminine", "guillemotleft", "notsign", "hyphen", "registered",
"macron", "degree", "plusminus", "twosuperior", "threesuperior", "acute", "mu", "paragraph",
"periodcentered", "cedilla", "onesuperior", "masculine", "guillemotright", "onequarter",
"onehalf", "threequarters", "questiondown", "Agrave", "Aacute", "Acircumflex", "Atilde",
"Adiaeresis", "Aring", "AE", "Ccedilla", "Egrave", "Eacute", "Ecircumflex", "Ediaeresis",
"Igrave", "Iacute", "Icircumflex", "Idiaeresis", "ETH", "Ntilde", "Ograve", "Oacute",
"Ocircumflex", "Otilde", "Odiaeresis", "multiply", "Oslash", "Ugrave", "Uacute",
"Ucircumflex", "Udiaeresis", "Yacute", "THORN", "ssharp", "agrave", "aacute", "acircumflex",
"atilde", "adiaeresis", "aring", "ae", "ccedilla", "egrave", "eacute", "ecircumflex",
"ediaeresis", "igrave", "iacute", "icircumflex", "idiaeresis", "eth", "ntilde", "ograve",
"oacute", "ocircumflex", "otilde", "odiaeresis", "division", "oslash", "ugrave", "uacute",
"ucircumflex", "udiaeresis", "yacute", "thorn", "ydiaeresis",
]
///| Other names that type a character.
let extra_names : Array[(String, Int)] = [
("EuroSign", 0x20ac),
("guillemetleft", 0xab),
("guillemetright", 0xbb),
("Ooblique", 0xd8),
("ooblique", 0xf8),
("masculine", 0xba),
("ordmasculine", 0xba),
("KP_0", 0x30),
("KP_1", 0x31),
("KP_2", 0x32),
("KP_3", 0x33),
("KP_4", 0x34),
("KP_5", 0x35),
("KP_6", 0x36),
("KP_7", 0x37),
("KP_8", 0x38),
("KP_9", 0x39),
("KP_Decimal", 0x2e),
("KP_Add", 0x2b),
("KP_Subtract", 0x2d),
("KP_Multiply", 0x2a),
("KP_Divide", 0x2f),
("KP_Space", 0x20),
("KP_Separator", 0x2c),
]
///|
let name_table : Ref[Map[String, Int]?] = { val: None }
///|
fn names() -> Map[String, Int] {
match name_table.val {
Some(m) => m
None => {
let m : Map[String, Int] = {}
for i, n in ascii_names {
m.set(n, 0x20 + i)
}
for i, n in latin1_names {
m.set(n, 0xa0 + i)
}
for e in extra_names {
m.set(e.0, e.1)
}
name_table.val = Some(m)
m
}
}
}
///|
fn hex_value(s : String) -> Int? {
let mut v = 0
if s.length() == 0 || s.length() > 8 {
return None
}
for c in s {
let d = if c >= '0' && c <= '9' {
c.to_int() - '0'.to_int()
} else if c >= 'a' && c <= 'f' {
c.to_int() - 'a'.to_int() + 10
} else if c >= 'A' && c <= 'F' {
c.to_int() - 'A'.to_int() + 10
} else {
return None
}
v = v * 16 + d
}
Some(v)
}
///| The character keysym `name` types, if any (dead keys, modifiers and unknown names: None).
pub fn keysym_char(name : String) -> Char? {
match names().get(name) {
Some(cp) => return Some(Int::unsafe_to_char(cp))
None => ()
}
let cp = if name.length() >= 5 && name.has_prefix("U") {
hex_value(name[1:].to_string())
} else if (name.length() == 9 || name.length() == 10) && name.has_prefix("0x100") {
hex_value(name[5:].to_string())
} else {
None
}
match cp {
Some(v) if v >= 0x20 && v < 0x110000 && !(v >= 0xd800 && v < 0xe000) && v != 0x7f =>
Some(Int::unsafe_to_char(v))
_ => None
}
}
///| Modifier bits of an xkb state (wl_keyboard.modifiers): Shift, Lock (Caps), Mod5 (AltGr).
pub let mask_shift : UInt = 1
///|
pub let mask_lock : UInt = 2
///|
pub let mask_ctrl : UInt = 4
///|
pub let mask_alt : UInt = 8
///|
pub let mask_altgr : UInt = 0x80
///| Whether `c` is a letter Caps Lock applies to: ASCII and Latin-1 letters, and anything past
/// Latin-1 (Cyrillic, Greek, ...), as long as its two levels differ (checked by the caller).
fn letter(c : Char) -> Bool {
let v = c.to_int()
c.is_ascii_alphabetic() || (v >= 0xc0 && v <= 0xff && v != 0xd7 && v != 0xf7) || v > 0x24f
}
///| The character evdev key `code` types with modifier `mods` (depressed | latched | locked)
/// in layout group `group`; None for keys that type nothing.
pub fn Keymap::char_for(self : Keymap, code : UInt, mods : UInt, group : UInt) -> Char? {
let ks = match self.keys.get(code.reinterpret_as_int() + 8) {
Some(k) => k
None => return None
}
let g = if group.reinterpret_as_int() < ks.groups.length() {
ks.groups[group.reinterpret_as_int()]
} else {
ks.groups[0]
}
if g.length() == 0 {
return None
}
let shift = (mods & mask_shift) != 0U
let altgr = (mods & mask_altgr) != 0U && g.length() > 2
let base = if altgr { 2 } else { 0 }
let at = fn(l : Int) -> Char? {
if l < g.length() {
keysym_char(g[l])
} else if l > 0 {
keysym_char(g[l - 1])
} else {
None
}
}
let mut level = base + (if shift { 1 } else { 0 })
// Caps Lock flips the case of letters (the ALPHABETIC key type), not digits or punctuation.
if (mods & mask_lock) != 0U {
match (at(base), at(base + 1)) {
(Some(lo), Some(up)) if lo != up && letter(lo) && letter(up) =>
level = base + (if shift { 0 } else { 1 })
_ => ()
}
}
at(level)
}
///| xkb keycode names of the US layout's keys (evdev + 8), for keymaps whose keycodes section
/// is missing.
fn us_codes() -> Map[String, Int] {
let m : Map[String, Int] = {}
let rows = [
("TLDE", 49),
("AE01", 10),
("AE02", 11),
("AE03", 12),
("AE04", 13),
("AE05", 14),
("AE06", 15),
("AE07", 16),
("AE08", 17),
("AE09", 18),
("AE10", 19),
("AE11", 20),
("AE12", 21),
("AD01", 24),
("AD02", 25),
("AD03", 26),
("AD04", 27),
("AD05", 28),
("AD06", 29),
("AD07", 30),
("AD08", 31),
("AD09", 32),
("AD10", 33),
("AD11", 34),
("AD12", 35),
("AC01", 38),
("AC02", 39),
("AC03", 40),
("AC04", 41),
("AC05", 42),
("AC06", 43),
("AC07", 44),
("AC08", 45),
("AC09", 46),
("AC10", 47),
("AC11", 48),
("BKSL", 51),
("AB01", 52),
("AB02", 53),
("AB03", 54),
("AB04", 55),
("AB05", 56),
("AB06", 57),
("AB07", 58),
("AB08", 59),
("AB09", 60),
("AB10", 61),
("SPCE", 65),
("LSGT", 94),
("KP7", 79),
("KP8", 80),
("KP9", 81),
("KPSU", 82),
("KP4", 83),
("KP5", 84),
("KP6", 85),
("KPAD", 86),
("KP1", 87),
("KP2", 88),
("KP3", 89),
("KP0", 90),
("KPDL", 91),
("KPDV", 106),
("KPMU", 63),
]
for r in rows {
m.set(r.0, r.1)
}
m
}
///| The US layout, used when there is no keymap.
let us_symbols : String =
#|xkb_symbols "us" {
#| key <TLDE> { [ grave, asciitilde ] };
#| key <AE01> { [ 1, exclam ] };
#| key <AE02> { [ 2, at ] };
#| key <AE03> { [ 3, numbersign ] };
#| key <AE04> { [ 4, dollar ] };
#| key <AE05> { [ 5, percent ] };
#| key <AE06> { [ 6, asciicircum ] };
#| key <AE07> { [ 7, ampersand ] };
#| key <AE08> { [ 8, asterisk ] };
#| key <AE09> { [ 9, parenleft ] };
#| key <AE10> { [ 0, parenright ] };
#| key <AE11> { [ minus, underscore ] };
#| key <AE12> { [ equal, plus ] };
#| key <AD01> { [ q, Q ] };
#| key <AD02> { [ w, W ] };
#| key <AD03> { [ e, E ] };
#| key <AD04> { [ r, R ] };
#| key <AD05> { [ t, T ] };
#| key <AD06> { [ y, Y ] };
#| key <AD07> { [ u, U ] };
#| key <AD08> { [ i, I ] };
#| key <AD09> { [ o, O ] };
#| key <AD10> { [ p, P ] };
#| key <AD11> { [ bracketleft, braceleft ] };
#| key <AD12> { [ bracketright, braceright ] };
#| key <AC01> { [ a, A ] };
#| key <AC02> { [ s, S ] };
#| key <AC03> { [ d, D ] };
#| key <AC04> { [ f, F ] };
#| key <AC05> { [ g, G ] };
#| key <AC06> { [ h, H ] };
#| key <AC07> { [ j, J ] };
#| key <AC08> { [ k, K ] };
#| key <AC09> { [ l, L ] };
#| key <AC10> { [ semicolon, colon ] };
#| key <AC11> { [ apostrophe, quotedbl ] };
#| key <BKSL> { [ backslash, bar ] };
#| key <AB01> { [ z, Z ] };
#| key <AB02> { [ x, X ] };
#| key <AB03> { [ c, C ] };
#| key <AB04> { [ v, V ] };
#| key <AB05> { [ b, B ] };
#| key <AB06> { [ n, N ] };
#| key <AB07> { [ m, M ] };
#| key <AB08> { [ comma, less ] };
#| key <AB09> { [ period, greater ] };
#| key <AB10> { [ slash, question ] };
#| key <SPCE> { [ space ] };
#| key <KP7> { [ KP_7 ] };
#| key <KP8> { [ KP_8 ] };
#| key <KP9> { [ KP_9 ] };
#| key <KP4> { [ KP_4 ] };
#| key <KP5> { [ KP_5 ] };
#| key <KP6> { [ KP_6 ] };
#| key <KP1> { [ KP_1 ] };
#| key <KP2> { [ KP_2 ] };
#| key <KP3> { [ KP_3 ] };
#| key <KP0> { [ KP_0 ] };
#| key <KPDL> { [ KP_Decimal ] };
#| key <KPAD> { [ KP_Add ] };
#| key <KPSU> { [ KP_Subtract ] };
#| key <KPMU> { [ KP_Multiply ] };
#| key <KPDV> { [ KP_Divide ] };
#|};
///| The keymap `text` describes, or the US layout when it is empty or unusable.
pub fn Keymap::from_text(text : String) -> Keymap {
match Keymap::parse(text) {
Some(k) => k
None => Keymap::us()
}
}
///| The built-in US layout.
pub fn Keymap::us() -> Keymap {
Keymap::parse(us_symbols).unwrap()
}
+17
View File
@@ -0,0 +1,17 @@
import {
"moonbitlang/core/builtin",
"moonbitlang/core/encoding/utf8" @utf8,
"chandra/desktop/compositor/network" @network,
"chandra/desktop/compositor/sys" @sys,
}
supported_targets = "+native+wasm"
warnings = "-44"
import {
"chandra/desktop/compositor/polkit" @polkit,
"chandra/desktop/compositor/network" @network,
"chandra/desktop/compositor/sys" @sys,
"moonbitlang/core/encoding/utf8" @utf8,
} for "test"
+327
View File
@@ -0,0 +1,327 @@
///| Keymaps, the helper protocol, request descriptions and the dialog's states.
///|
fn type_keys(km : @polkit.Keymap, keys : Array[(UInt, UInt)]) -> String {
let sb = StringBuilder::new()
for k in keys {
match km.char_for(k.0, k.1, 0U) {
Some(c) => sb.write_char(c)
None => ()
}
}
sb.to_string()
}
///|
test "the built-in US layout types letters, shifted symbols and Caps Lock letters" {
let km = @polkit.Keymap::us()
// h i ! with shift on 1, then 'a' with Caps Lock, '1' with Caps Lock stays a digit.
assert_eq(type_keys(km, [(35U, 0U), (23U, 0U), (2U, 1U), (30U, 2U), (2U, 2U), (30U, 3U)]), "hi!A1a")
assert_eq(km.char_for(57U, 0U, 0U), Some(' '))
assert_eq(km.char_for(1U, 0U, 0U), None) // Escape types nothing
}
///| What xkbcommon's xkb_keymap_get_as_string writes (abridged), German layout in group 2.
let xkb_text : String =
#|xkb_keymap {
#|xkb_keycodes "evdev+aliases(qwertz)" {
#| minimum = 8;
#| maximum = 255;
#| <AE01> = 10;
#| <AD06> = 29;
#| <AB01> = 52;
#| <AC11> = 48;
#| alias <ALT1> = <AE01>;
#|};
#|xkb_types "complete" {
#| type "ALPHABETIC" { modifiers= Shift+Lock; };
#|};
#|xkb_symbols "pc+us+de:2" {
#| name[Group1]="English (US)";
#| key <AE01> { [ 1, exclam ], [ 1, exclam, onesuperior, exclamdown ] };
#| key <AD06> {
#| type= "ALPHABETIC",
#| symbols[1]= [ y, Y ],
#| symbols[2]= [ z, Z ]
#| };
#| key <AB01> {
#| type[Group1]= "ALPHABETIC",
#| symbols[Group1]= [ z, Z ],
#| symbols[Group2]= [ y, Y, guillemotright, U203A ]
#| };
#| key <AC11> { [ apostrophe, quotedbl ], [ adiaeresis, Adiaeresis, dead_circumflex, dead_caron ] };
#| modifier_map Shift { <LFSH> };
#|};
#|};
///|
test "an xkbcommon keymap: groups, levels, AltGr and Latin-1 keysyms" {
let km = @polkit.Keymap::from_text(xkb_text)
assert_eq(km.char_for(21U, 0U, 0U), Some('y')) // AD06, group 1
assert_eq(km.char_for(21U, 0U, 1U), Some('z')) // group 2 (German)
assert_eq(km.char_for(21U, 1U, 1U), Some('Z'))
assert_eq(km.char_for(44U, 0U, 1U), Some('y')) // AB01 in group 2
assert_eq(km.char_for(44U, 0x80U, 1U), Some('»')) // AltGr: level 3
assert_eq(km.char_for(44U, 0x81U, 1U), Some('›')) // AltGr+Shift: level 4, U203A
assert_eq(km.char_for(40U, 0U, 1U), Some('ä'))
assert_eq(km.char_for(40U, 2U, 1U), Some('Ä')) // Caps Lock
assert_eq(km.char_for(40U, 0x80U, 1U), None) // a dead key types nothing by itself
assert_eq(km.char_for(2U, 1U, 0U), Some('!'))
// Keys the keymap doesn't have type nothing.
assert_eq(km.char_for(30U, 0U, 0U), None)
}
///|
test "keysym names" {
assert_eq(@polkit.keysym_char("at"), Some('@'))
assert_eq(@polkit.keysym_char("EuroSign"), Some('€'))
assert_eq(@polkit.keysym_char("U0431"), Some('б'))
assert_eq(@polkit.keysym_char("0x10020ac"), Some('€'))
assert_eq(@polkit.keysym_char("Shift_L"), None)
}
///|
test "helper lines are unescaped as g_strcompress does" {
assert_eq(@polkit.parse_helper_line("PAM_PROMPT_ECHO_OFF Password: "), Some(PromptEchoOff("Password: ")))
assert_eq(@polkit.parse_helper_line("PAM_PROMPT_ECHO_ON Verification code:"), Some(PromptEchoOn("Verification code:")))
assert_eq(
@polkit.parse_helper_line("PAM_ERROR_MSG The account is locked due to 3 failed logins.\\n(5 minutes left to unlock)"),
Some(ErrorMsg("The account is locked due to 3 failed logins.\n(5 minutes left to unlock)")),
)
assert_eq(@polkit.parse_helper_line("PAM_TEXT_INFO Place your finger on the \\\"reader\\\""), Some(TextInfo("Place your finger on the \"reader\"")))
// Octal escapes are bytes of UTF-8.
assert_eq(@polkit.unescape("caf\\303\\251"), "café")
assert_eq(@polkit.parse_helper_line("SUCCESS"), Some(Success))
assert_eq(@polkit.parse_helper_line("FAILURE"), Some(Failure))
assert_eq(@polkit.parse_helper_line("polkit-agent-helper-1: noise"), None)
}
///|
test "run0 command lines" {
assert_eq(@polkit.parse_run0(["run0", "gparted"]), ("root", ["gparted"]))
assert_eq(@polkit.parse_run0(["/usr/bin/run0", "-u", "nandi", "--setenv", "A=1", "ls", "-la", "/root"]), ("nandi", ["ls", "-la", "/root"]))
assert_eq(@polkit.parse_run0(["run0", "--user=postgres", "--", "psql", "-c", "select 1"]), ("postgres", ["psql", "-c", "select 1"]))
assert_eq(@polkit.parse_run0(["run0", "--background=41"]), ("root", []))
assert_eq(@polkit.command_text(["psql", "-c", "select 1", "it's"]), "psql -c 'select 1' 'it'\\''s'")
assert_eq(@polkit.run0_unit_pid("run-p15802-i1990.service"), Some(15802))
assert_eq(@polkit.run0_unit_pid("run-u12.service"), None)
assert_eq(@polkit.quoted_in("Authentication is required to start transient unit 'run-p15802-i1990.service'."), "run-p15802-i1990.service")
}
///|
fn request(action : String, message : String, details : Map[String, String]) -> @polkit.AuthRequest {
{
action_id: action,
message,
icon_name: "",
details,
cookie: "3-abc-1-def",
users: [{ uid: 1000, name: "nandi", real_name: "Nandi" }],
}
}
///|
test "describe: run0 shows the command it will run, not the unit name" {
let req = request(
"org.freedesktop.systemd1.manage-units",
"Authentication is required to start transient unit 'run-p15802-i1990.service'.",
{ "unit": "run-p15802-i1990.service", "verb": "start", "polkit.subject-pid": "15802", "polkit.caller-pid": "1" },
)
let d = @polkit.describe(req, cmdline=pid => if pid == 15802 { ["run0", "gparted", "/dev/sda"] } else { [] }, who=pid => "run0 (pid " + pid.to_string() + ")")
assert_eq(d.title, "Run a command as root")
assert_eq(d.subtitle, "run0 needs your password to run this as root:")
assert_eq(d.command, "gparted /dev/sda")
assert_eq(d.program, "gparted")
assert_eq(d.details, [("Requested by", "run0 (pid 15802)"), ("Runs as", "root"), ("Unit", "run-p15802-i1990.service"), ("Action", "org.freedesktop.systemd1.manage-units")])
// Without details (older systemd), the unit name in the message still finds run0.
let bare = request("org.freedesktop.systemd1.manage-units", req.message, {})
let d2 = @polkit.describe(bare, cmdline=pid => if pid == 15802 { ["run0"] } else { [] }, who=_ => "")
assert_eq(d2.title, "Open a shell as root")
assert_eq(d2.command, "")
}
///|
test "describe: pkexec and other actions" {
let pk = request("org.freedesktop.policykit.exec", "Authentication is needed to run `/usr/bin/gparted' as the super user", {
"program": "/usr/bin/gparted",
"command_line": "/usr/bin/gparted",
"user": "root",
})
let d = @polkit.describe(pk, cmdline=_ => [], who=_ => "")
assert_eq(d.title, "Run a program as root")
assert_eq(d.command, "/usr/bin/gparted")
assert_eq(d.program, "gparted")
let other = request("org.freedesktop.udisks2.filesystem-mount-system", "Authentication is required to mount the drive", {})
let d3 = @polkit.describe(other, cmdline=_ => [], who=_ => "")
assert_eq(d3.title, "Authentication is required to mount the drive")
assert_eq(d3.command, "")
assert_eq(d3.details, [("Action", "org.freedesktop.udisks2.filesystem-mount-system")])
}
///|
test "identities: users, group members, the user at the screen first" {
let passwd = @polkit.parse_passwd("root:x:0:0:root:/root:/bin/bash\nnandi:x:1000:1000:Nandi Devi,,,:/home/nandi:/bin/bash\nada:x:1001:1001::/home/ada:/bin/sh\n")
let groups = @polkit.parse_group("root:x:0:\nwheel:x:10:ada,nandi\n")
let ids : Array[@network.DValue] = [
Struct([Str("unix-user"), @network.dict("v", [("uid", Variant(U32(0)))])]),
Struct([Str("unix-group"), @network.dict("v", [("gid", Variant(U32(10)))])]),
]
let users = @polkit.users_for_identities(ids, passwd, groups, 1000)
assert_eq(users.map(u => u.name), ["nandi", "root", "ada"])
assert_eq(users[0].real_name, "Nandi Devi")
}
///|
fn dialog(users : Int) -> @polkit.AuthDialog {
let us : Array[@polkit.AuthUser] = [{ uid: 1000, name: "nandi", real_name: "Nandi" }, { uid: 0, name: "root", real_name: "root" }]
let req = { ..request("a", "m", {}), users: us[:users].to_array() }
@polkit.AuthDialog::new(req, @polkit.describe(req, cmdline=_ => [], who=_ => ""))
}
///|
fn answer_text(e : @polkit.DialogEffect) -> String {
match e {
Answer(b) => {
let s = @utf8.decode_lossy(Bytes::makei(b.length(), i => b[i]))
@polkit.zero(b)
s
}
_ => "<none>"
}
}
///|
test "dialog: type, submit, wrong password, retry, success" {
let d = dialog(1)
let km = @polkit.Keymap::us()
let type_str = fn(s : String) {
for c in s {
ignore(d.key(0U, 0U, Some(c)))
}
}
// Typing before PAM's prompt is kept; Enter waits for it.
type_str("hunter")
assert_true(d.key(@polkit.key_enter, 0U, None) is Nothing)
assert_eq(answer_text(d.helper(PromptEchoOff("Password: "), 10UL)), "hunter")
assert_eq(d.phase, Checking)
assert_eq(d.typed(), 0) // wiped once sent
// Typing is ignored while PAM checks.
ignore(d.key(30U, 0U, km.char_for(30U, 0U, 0U)))
assert_eq(d.typed(), 0)
// Wrong: error, shake, field cleared, the helper restarts.
assert_true(d.helper(Failure, 100UL) is Restart)
assert_eq(d.error, "Wrong password. Try again.")
assert_eq(d.failures, 1)
assert_true(d.shaking(200UL))
assert_false(d.shaking(600UL))
assert_true(d.shake_offset(100UL + 35UL) != 0)
assert_eq(d.phase, Starting)
assert_true(d.helper(PromptEchoOff("Password: "), 700UL) is Nothing)
assert_eq(d.prompt, "Password")
type_str("hunter2")
assert_eq(d.error, "") // typing again clears it
assert_eq(d.field_text(), "●●●●●●●")
ignore(d.activate(Reveal))
d.activate(Field) |> ignore
assert_eq(d.field_text(), "hunter2")
// Backspace, then Enter sends.
ignore(d.key(@polkit.key_backspace, 0U, None))
type_str("2")
assert_eq(answer_text(d.key(@polkit.key_enter, 0U, None)), "hunter2")
assert_true(d.helper(Success, 900UL) is Authorized)
}
///|
test "dialog: PAM messages, lockout, echo-on prompts, fingerprint" {
let d = dialog(1)
// A fingerprint module only informs; the dialog waits with its message.
ignore(d.helper(TextInfo("Place your finger on the fingerprint reader"), 1UL))
assert_eq(d.phase, Waiting)
assert_eq(d.info, "Place your finger on the fingerprint reader")
// Then falls back to a password.
ignore(d.helper(PromptEchoOff("Password: "), 2UL))
assert_eq(d.phase, Prompt)
assert_eq(d.info, "")
// An error from PAM (faillock) is shown as is after the failure.
ignore(d.helper(ErrorMsg("The account is locked due to 3 failed logins."), 3UL))
ignore(d.helper(Failure, 4UL))
assert_eq(d.error, "The account is locked due to 3 failed logins.")
// A visible prompt (a one-time code): typed text is shown, even empty answers go.
ignore(d.helper(PromptEchoOn("Verification code: "), 5UL))
assert_true(d.echo)
ignore(d.key(0U, 0U, Some('4')))
assert_eq(d.field_text(), "4")
assert_eq(answer_text(d.key(@polkit.key_kp_enter, 0U, None)), "4")
}
///|
test "dialog: keyboard focus, Escape, Space toggles, user picker" {
let d = dialog(2)
assert_eq(d.focus, Field)
assert_eq(d.focus_order(), [Field, User, Reveal, Details, Cancel, Allow])
ignore(d.key(@polkit.key_tab, 0U, None))
assert_eq(d.focus, User)
assert_true(d.key(@polkit.key_right, 0U, None) is Restart)
assert_eq(d.user().map(u => u.name), Some("root"))
ignore(d.key(@polkit.key_tab, 0U, None))
ignore(d.key(@polkit.key_space, 0U, None))
assert_true(d.reveal)
ignore(d.key(@polkit.key_tab, 0U, None))
ignore(d.key(@polkit.key_enter, 0U, None))
assert_true(d.details_open)
ignore(d.key(@polkit.key_tab, 1U, None)) // Shift+Tab goes back
assert_eq(d.focus, Reveal)
// Typing anywhere goes to the field.
ignore(d.key(0U, 0U, Some('x')))
assert_eq(d.focus, Field)
// Alt+D toggles details from the field; Ctrl+U clears it.
ignore(d.key(@polkit.key_d, 8U, Some('d')))
assert_false(d.details_open)
ignore(d.key(@polkit.key_u, 4U, Some('u')))
assert_eq(d.typed(), 0)
assert_true(d.key(@polkit.key_esc, 0U, None) is Cancelled)
// One user: no picker in the Tab order.
assert_eq(dialog(1).focus_order(), [Field, Reveal, Details, Cancel, Allow])
}
///|
test "the setuid route: the helper runs on a socket pair and speaks the protocol" {
// A stand-in for polkit-agent-helper-1: user name as argv[1], cookie then answer on stdin.
let script = "/tmp/chandra-fake-helper-" + @sys.getpid().to_string()
ignore(
@sys.write_file_bytes(
script,
@utf8.encode(
"#!/bin/sh\nread cookie\n[ \"$1\" = nandi ] && [ \"$cookie\" = c-1 ] || { echo FAILURE; exit 1; }\necho 'PAM_TEXT_INFO hello\\\\tthere'\necho 'PAM_PROMPT_ECHO_OFF Password: '\nread pw\nif [ \"$pw\" = 'pässword' ]; then echo SUCCESS; else echo FAILURE; fi\n",
),
),
)
ignore(@sys.spawn("chmod +x " + script, ""))
@sys.sleep_ms(200)
let s = @polkit.HelperSession::start(Program(script), "nandi", "c-1").unwrap()
let got : Array[@polkit.HelperEvent] = []
for i = 0; i < 200 && got.length() < 2; i = i + 1 {
ignore(@sys.poll_read(s.fd(), 10))
got.append(s.read())
}
assert_eq(got, [TextInfo("hello\tthere"), PromptEchoOff("Password: ")])
let answer : FixedArray[Byte] = FixedArray::make(9, b'\x00')
let b = @utf8.encode("pässword")
for i = 0; i < b.length(); i = i + 1 {
answer[i] = b[i]
}
assert_true(s.respond(answer))
let end : Array[@polkit.HelperEvent] = []
for i = 0; i < 200 && end.length() < 1; i = i + 1 {
ignore(@sys.poll_read(s.fd(), 10))
end.append(s.read())
}
assert_eq(end, [Success])
// The helper exits: the session notices without inventing a second verdict.
for i = 0; i < 50 && s.fd() >= 0; i = i + 1 {
ignore(@sys.poll_read(s.fd(), 10))
assert_eq(s.read(), [])
}
s.close()
@sys.unlink(script)
}
+207
View File
@@ -0,0 +1,207 @@
///| What polkit asks the agent to authenticate (BeginAuthentication), and who could answer.
///| A user who can authenticate: uid, login name and real name (from the passwd database).
pub(all) struct AuthUser {
uid : Int
name : String
real_name : String
} derive(Eq, Debug)
///| One BeginAuthentication call.
pub(all) struct AuthRequest {
action_id : String
/// polkit's translated message ("Authentication is required to ...").
message : String
icon_name : String
details : Map[String, String]
cookie : String
/// The users that may answer (unix-user identities, and the members of unix-group ones).
users : Array[AuthUser]
}
///| A detail by key, "" when absent.
pub fn AuthRequest::detail(self : AuthRequest, key : String) -> String {
self.details.get(key).unwrap_or("")
}
///| A passwd/group database line split on ':'.
fn fields(line : String) -> Array[String] {
line.split(":").map(v => v.to_string()).to_array()
}
///| Parse /etc/passwd text: uid -> (name, real name). The real name is GECOS up to its first ','.
pub fn parse_passwd(text : String) -> Map[Int, (String, String)] {
let out : Map[Int, (String, String)] = {}
for raw in text.split("\n") {
let f = fields(raw.to_string())
if f.length() < 5 {
continue
}
let uid = match parse_uint(f[2]) {
Some(v) => v
None => continue
}
let gecos = match f[4].find(",") {
Some(i) => f[4][:i].to_string()
None => f[4]
}
if !out.contains(uid) {
out.set(uid, (f[0], gecos))
}
}
out
}
///| Parse /etc/group text: gid -> member names.
pub fn parse_group(text : String) -> Map[Int, Array[String]] {
let out : Map[Int, Array[String]] = {}
for raw in text.split("\n") {
let f = fields(raw.to_string())
if f.length() < 4 {
continue
}
let gid = match parse_uint(f[2]) {
Some(v) => v
None => continue
}
let members = f[3].split(",").map(v => v.to_string().trim(chars=" ").to_string()).filter(v => v != "").to_array()
out.set(gid, members)
}
out
}
///| A decimal number.
fn parse_uint(s : String) -> Int? {
if s.length() == 0 || s.length() > 10 {
return None
}
let mut v = 0
for c in s {
if c < '0' || c > '9' {
return None
}
v = v * 10 + (c.to_int() - '0'.to_int())
}
Some(v)
}
///| The users polkit's identities (a(sa{sv}): ("unix-user", {uid}) or ("unix-group", {gid}))
/// stand for, in order, without repeats; a group stands for its members. `self_uid` (the user
/// at the screen) is listed first when it is among them, as other agents do.
pub fn users_for_identities(
identities : Array[@network.DValue],
passwd : Map[Int, (String, String)],
groups : Map[Int, Array[String]],
self_uid : Int,
) -> Array[AuthUser] {
let out : Array[AuthUser] = []
let by_name : Map[String, Int] = {}
for uid, e in passwd {
by_name.set(e.0, uid)
}
let add = fn(uid : Int) {
if out.iter().any(u => u.uid == uid) {
return
}
let (name, real_name) = match passwd.get(uid) {
Some(e) => e
None => (uid.to_string(), "")
}
out.push({ uid, name, real_name })
}
let num = fn(v : @network.DValue) -> Int? {
match v {
Variant(inner) =>
match inner {
U32(x) => Some(x.reinterpret_as_int())
I32(x) => Some(x)
_ => None
}
U32(x) => Some(x.reinterpret_as_int())
I32(x) => Some(x)
_ => None
}
}
for id in identities {
match id {
Struct([Str(kind), Arr(_, entries)]) =>
for e in entries {
match e {
Entry(Str(k), v) =>
match (kind, k, num(v)) {
("unix-user", "uid", Some(uid)) => add(uid)
("unix-group", "gid", Some(gid)) =>
for m in groups.get(gid).unwrap_or([]) {
match by_name.get(m) {
Some(uid) => add(uid)
None => ()
}
}
_ => ()
}
_ => ()
}
}
_ => ()
}
}
// The user at the screen first.
match out.search_by(u => u.uid == self_uid) {
Some(i) if i > 0 => {
let me = out.remove(i)
out.insert(0, me)
}
_ => ()
}
out
}
///| A string-to-string dict (a{ss}) as a map.
pub fn string_dict(v : @network.DValue) -> Map[String, String] {
let out : Map[String, String] = {}
match v {
Arr(_, entries) =>
for e in entries {
match e {
Entry(Str(k), Str(x)) => out.set(k, x)
_ => ()
}
}
_ => ()
}
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"))
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()
if parts.length() > 0 {
return parse_uint(parts[0].to_string().trim(chars=" ").to_string()).unwrap_or(-1)
}
}
}
-1
}
///| 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? {
match args {
[Str(action_id), Str(message), Str(icon_name), details, Str(cookie), Arr(_, ids)] => {
let passwd = parse_passwd(@utf8.decode_lossy(@sys.read_file_bytes("/etc/passwd")))
let groups = parse_group(@utf8.decode_lossy(@sys.read_file_bytes("/etc/group")))
let me = own_uid()
// Users outside /etc/passwd (systemd-homed, LDAP): the one at the screen is $USER.
if me >= 0 && !passwd.contains(me) && @sys.getenv("USER") != "" {
passwd.set(me, (@sys.getenv("USER"), ""))
}
let users = users_for_identities(ids, passwd, groups, me)
Some({ action_id, message, icon_name, details: string_dict(details), cookie, users })
}
_ => None
}
}
+18
View File
@@ -523,3 +523,21 @@ fn DesktopShell::publish_icons(self : DesktopShell) -> Unit {
@wasm.publish(Icons, t) @wasm.publish(Icons, t)
} }
///| The image handle of theme icon `name` (say "drive-harddisk"; 0: none), cached.
pub fn DesktopShell::theme_icon(self : DesktopShell, name : String) -> UInt {
if name == "" {
return 0U
}
let key = "icon:" + name
match self.icon_handles.get(key) {
Some(h) => return h
None => ()
}
let h = match self.icon_search().find(name, @sys.host_raster()) {
Some(path) => @raster.load_image(path)
None => 0U
}
self.icon_handles.set(key, h)
h
}
+6
View File
@@ -155,6 +155,8 @@ pub(all) enum ShellAction {
Logout Logout
/// The Dark mode setting changed: the compositor swaps the theme (see `dark_mode`). /// The Dark mode setting changed: the compositor swaps the theme (see `dark_mode`).
ThemeChanged ThemeChanged
/// The password dialog setting changed: the compositor registers its polkit agent or leaves.
AuthAgentChanged
/// The screenshot module asked for a screenshot or recording (code: see the compositor's /// The screenshot module asked for a screenshot or recording (code: see the compositor's
/// screenshot_request). /// screenshot_request).
Screenshot(Int) Screenshot(Int)
@@ -272,6 +274,9 @@ pub(all) struct DesktopShell {
/// The network service (network.mbt), while a module imports `network`. /// The network service (network.mbt), while a module imports `network`.
mut net : @network.NetService? mut net : @network.NetService?
mut remember_windows : Bool mut remember_windows : Bool
/// Chandra's own password dialog answers polkit (run0, pkexec, ...); off: the system's polkit
/// agent does. Saved as state.edn `:auth-agent :system` when off.
mut native_auth_agent : Bool
/// Dark mode (the configured theme) or light (Moon Day); saved as `:theme :light` when off. /// Dark mode (the configured theme) or light (Moon Day); saved as `:theme :light` when off.
mut dark_mode : Bool mut dark_mode : Bool
/// Power: minutes without input before the login session turns the screen off / suspends /// Power: minutes without input before the login session turns the screen off / suspends
@@ -406,6 +411,7 @@ pub fn DesktopShell::new(display : String) -> DesktopShell {
screenshot_state: 2, screenshot_state: 2,
net: None, net: None,
remember_windows: true, remember_windows: true,
native_auth_agent: true,
dark_mode: true, dark_mode: true,
screen_off_min: default_screen_off_min, screen_off_min: default_screen_off_min,
suspend_min: default_suspend_min, suspend_min: default_suspend_min,
+19 -2
View File
@@ -19,7 +19,9 @@
/// ; the next start (see session.mbt in compositor/host) /// ; the next start (see session.mbt in compositor/host)
/// :restore-session false ; don't reopen them (absent: reopen); the session settings module /// :restore-session false ; don't reopen them (absent: reopen); the session settings module
/// ; or a hand edit sets it /// ; or a hand edit sets it
/// :remember-windows false} ; don't place windows where they were left (absent: do) /// :remember-windows false ; don't place windows where they were left (absent: do)
/// :auth-agent :system} ; passwords for run0/pkexec/polkit go to the system's polkit
/// ; agent instead of Chandra's own dialog (absent: :chandra)
/// ///
/// Saving merges into what is already in the file, so keys this build doesn't know (a future /// Saving merges into what is already in the file, so keys this build doesn't know (a future
/// widget's state, hand-written notes) survive. Everything is a no-op unless `persist` is on /// widget's state, hand-written notes) survive. Everything is a no-op unless `persist` is on
@@ -47,6 +49,8 @@ pub(all) struct SavedState {
shortcuts : Array[(String, String)] shortcuts : Array[(String, String)]
/// From `:terminal`: the chosen terminal's desktop id. /// From `:terminal`: the chosen terminal's desktop id.
terminal : String? terminal : String?
/// From `:auth-agent`: true for :chandra, false for :system.
native_auth_agent : Bool?
} }
///| ///|
@@ -60,7 +64,7 @@ let layout_names : Array[String] = ["tiling", "monocle", "floating"]
///| The keys this build owns; everything else in the file is kept as it is. ///| The keys this build owns; everything else in the file is kept as it is.
let owned_keys : Array[String] = [ let owned_keys : Array[String] = [
"layout", "recent", "desktop-card", "windows", "wallpaper", "restore-session", "remember-windows", "layout", "recent", "desktop-card", "windows", "wallpaper", "restore-session", "remember-windows",
"theme", "power", "shortcuts", "terminal", "theme", "power", "shortcuts", "terminal", "auth-agent",
] ]
///| How state.edn names each wallpaper, in `@libshell.wallpaper_names` order. ///| How state.edn names each wallpaper, in `@libshell.wallpaper_names` order.
@@ -108,6 +112,7 @@ pub fn DesktopShell::load_state(self : DesktopShell) -> SavedState {
power: (None, None), power: (None, None),
shortcuts: [], shortcuts: [],
terminal: None, terminal: None,
native_auth_agent: None,
} }
} }
let entries = read_state_file() let entries = read_state_file()
@@ -223,6 +228,11 @@ pub fn DesktopShell::load_state(self : DesktopShell) -> SavedState {
Some(Text(t)) if t.length() > 0 => Some(t) Some(Text(t)) if t.length() > 0 => Some(t)
_ => None _ => None
}, },
native_auth_agent: match lookup_key(entries, "auth-agent") {
Some(Keyword("system")) => Some(false)
Some(Keyword("chandra")) => Some(true)
_ => None
},
shortcuts: match lookup_key(entries, "shortcuts") { shortcuts: match lookup_key(entries, "shortcuts") {
Some(Mapping(m)) => { Some(Mapping(m)) => {
let out : Array[(String, String)] = [] let out : Array[(String, String)] = []
@@ -274,6 +284,10 @@ pub fn DesktopShell::apply_state(self : DesktopShell, st : SavedState) -> Unit {
_ => () _ => ()
} }
self.shortcuts.apply_saved(st.shortcuts) self.shortcuts.apply_saved(st.shortcuts)
match st.native_auth_agent {
Some(b) => self.native_auth_agent = b
None => ()
}
match st.terminal { match st.terminal {
Some(t) => { Some(t) => {
self.terminal = t self.terminal = t
@@ -371,6 +385,9 @@ pub fn DesktopShell::save_state(self : DesktopShell) -> Unit {
changed.map(c => (@edn.Value::Keyword(c.0), @edn.Value::Text(c.1))), changed.map(c => (@edn.Value::Keyword(c.0), @edn.Value::Text(c.1))),
))) )))
} }
if !self.native_auth_agent {
entries.insert(2, (@edn.Value::Keyword("auth-agent"), @edn.Value::Keyword("system")))
}
if !self.dark_mode { if !self.dark_mode {
entries.insert(2, (@edn.Value::Keyword("theme"), @edn.Value::Keyword("light"))) entries.insert(2, (@edn.Value::Keyword("theme"), @edn.Value::Keyword("light")))
} }
+8 -2
View File
@@ -733,14 +733,15 @@ pub fn DesktopShell::set_wallpaper(self : DesktopShell, i : Int) -> Unit {
///| The session settings the session settings module lists, in index order. ///| The session settings the session settings module lists, in index order.
let session_setting_names : Array[String] = [ let session_setting_names : Array[String] = [
"Reopen windows at login", "Remember window positions", "Dark mode", "Reopen windows at login", "Remember window positions", "Dark mode", "Chandra password dialog",
] ]
///| Which session settings are on: bit i for `session_setting_names[i]`. ///| Which session settings are on: bit i for `session_setting_names[i]`.
fn DesktopShell::session_settings_bits(self : DesktopShell) -> Int { fn DesktopShell::session_settings_bits(self : DesktopShell) -> Int {
(if self.restore_session { 1 } else { 0 }) | (if self.restore_session { 1 } else { 0 }) |
(if self.remember_windows { 2 } else { 0 }) | (if self.remember_windows { 2 } else { 0 }) |
(if self.dark_mode { 4 } else { 0 }) (if self.dark_mode { 4 } else { 0 }) |
(if self.native_auth_agent { 8 } else { 0 })
} }
///| Turn session setting `i` on or off (ignored when out of range) and remember it in state.edn. ///| Turn session setting `i` on or off (ignored when out of range) and remember it in state.edn.
@@ -753,6 +754,11 @@ pub fn DesktopShell::set_session_setting(self : DesktopShell, i : Int, on : Bool
self.dark_mode = on self.dark_mode = on
self.actions.push(ThemeChanged) self.actions.push(ThemeChanged)
} }
3 =>
if self.native_auth_agent != on {
self.native_auth_agent = on
self.actions.push(AuthAgentChanged)
}
_ => return _ => return
} }
@wasm.publish_session_settings(self.session_settings_bits()) @wasm.publish_session_settings(self.session_settings_bits())
+9
View File
@@ -253,6 +253,15 @@ pub fn spawn(cmd : String, display : String) -> Bool {
c_spawn(str_to_utf8_bytes(cmd), str_to_utf8_bytes(display)) == 0 c_spawn(str_to_utf8_bytes(cmd), str_to_utf8_bytes(display)) == 0
} }
///|
extern "C" fn c_spawn_socket(argv : Bytes) -> Int = "mp_spawn_socket"
///| Run `argv` (an absolute program path, then its arguments) with its stdin and stdout on a
/// socket and return our end of it (-1 on failure). For polkit's authentication helper.
pub fn spawn_socket(argv : Array[String]) -> Int {
c_spawn_socket(str_to_utf8_bytes(argv.join("\n")))
}
///| ///|
extern "C" fn c_take_sigusr1() -> Int = "mp_take_sigusr1" extern "C" fn c_take_sigusr1() -> Int = "mp_take_sigusr1"
+41
View File
@@ -10,6 +10,7 @@
#include <sys/socket.h> #include <sys/socket.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/un.h> #include <sys/un.h>
#include <sys/wait.h>
#include <time.h> #include <time.h>
#include <signal.h> #include <signal.h>
#include <sys/prctl.h> #include <sys/prctl.h>
@@ -565,3 +566,43 @@ moonbit_bytes_t mp_read_proc(moonbit_bytes_t path_bytes) {
memcpy(out, buf, n); memcpy(out, buf, n);
return out; return out;
} }
/* Run a program with its stdin and stdout on one end of a socket pair and return the other end
* (-1 on failure). `argv_bytes` holds the arguments separated by '\n'. stderr is inherited (the
* session log). The child is not waited for: SIGCHLD is ignored (see mp_spawn) or it is reaped
* by the double fork below. Used for polkit's setuid authentication helper. */
MOONBIT_FFI_EXPORT
int32_t mp_spawn_socket(moonbit_bytes_t argv_bytes) {
size_t n = Moonbit_array_length(argv_bytes);
char *buf = malloc(n + 1);
if (!buf) return -1;
memcpy(buf, argv_bytes, n);
buf[n] = 0;
char *argv[16];
int argc = 0;
char *save = NULL;
for (char *a = strtok_r(buf, "\n", &save); a && argc < 15; a = strtok_r(NULL, "\n", &save)) argv[argc++] = a;
argv[argc] = NULL;
if (argc == 0) { free(buf); return -1; }
int sv[2];
if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sv) != 0) { free(buf); return -1; }
pid_t pid = fork();
if (pid < 0) { close(sv[0]); close(sv[1]); free(buf); return -1; }
if (pid == 0) {
/* Double fork so the helper is never our zombie. */
pid_t inner = fork();
if (inner != 0) _exit(inner < 0 ? 1 : 0);
signal(SIGCHLD, SIG_DFL);
signal(SIGPIPE, SIG_DFL);
dup2(sv[1], 0);
dup2(sv[1], 1);
for (int fd = 3; fd < 1024; fd++) close(fd);
execv(argv[0], argv);
_exit(127);
}
close(sv[1]);
free(buf);
int status;
waitpid(pid, &status, 0);
return sv[0];
}
+6
View File
@@ -193,6 +193,12 @@ pub fn has_exe(name : String) -> Bool {
@hostsys.has_exe(name) @hostsys.has_exe(name)
} }
///| Run `argv` (an absolute program path, then its arguments) with its stdin and stdout on a
/// socket and return our end of it (-1 on failure). For polkit's authentication helper.
pub fn spawn_socket(argv : Array[String]) -> Int {
@hostsys.spawn_socket(argv.join("\n"))
}
///| Launch `cmd` detached with WAYLAND_DISPLAY set to `display`. ///| Launch `cmd` detached with WAYLAND_DISPLAY set to `display`.
pub fn spawn(cmd : String, display : String) -> Bool { pub fn spawn(cmd : String, display : String) -> Bool {
@hostsys.spawn(cmd, display) @hostsys.spawn(cmd, display)
+58
View File
@@ -0,0 +1,58 @@
# The password dialog (polkit agent)
When run0, pkexec, a disk mount or any other polkit-checked action needs an administrator's
password, Chandra asks in its own dialog: a card in the middle of a dimmed screen, drawn by the
compositor in the shell layer, above every window and client menu.
- **What it says.** For run0 the dialog shows the command that will run (`gparted /dev/sda`) and as
whom, instead of polkit's "start transient unit 'run-p15802-i1990.service'": the unit name
carries run0's pid, and run0's command line says what it runs. pkexec's command comes from
polkit's details. Everything else shows polkit's own message. Details (Alt+D) lists who asked
(process and its parent), the target user, the unit and the polkit action id.
- **Who answers.** The account polkit wants: you when you are an administrator, else one of the
admins (members of `wheel`/`sudo` are expanded). With several, Tab to the account row and use
← →.
- **Keyboard.** The field has the focus. Enter authenticates, Esc cancels, Tab / Shift+Tab move
between the account, Show, Details, Cancel and Authenticate, Space or Enter activates them.
Alt+R shows or hides the password, Ctrl+U clears it. Typing goes through the same xkb keymap
apps get (groups, Shift, AltGr, Caps Lock), so the password is typed on your layout. Caps Lock
on shows a warning.
- **PAM.** The dialog follows whatever PAM asks through polkit's helper: password prompts, visible
prompts (a one-time code), information (a fingerprint reader asking for a finger) and errors
(faillock's "account is locked"). A wrong password shakes the card, says so, and starts again.
While PAM checks, the field is locked and a spinner shows.
- **Safety.** While the dialog is up no client has keyboard focus, input goes to the dialog only,
and client popups are hidden, so nothing can draw over it or read the keys. The password is kept
as characters wiped after sending, the buffer sent to the helper is zeroed, and nothing of it is
logged.
## How it works
- `compositor/polkit/agent.mbt`: connects to the system bus with the compositor's own D-Bus code
and calls `RegisterAuthenticationAgent` on `org.freedesktop.PolicyKit1.Authority` for the login
session (`XDG_SESSION_ID`, else logind's session of the compositor's pid). It serves
`org.freedesktop.PolicyKit1.AuthenticationAgent` at `/org/chandra/PolicyKit1/AuthenticationAgent`:
`BeginAuthentication` calls queue up and are answered when the dialog is done (an empty reply
after success, `org.freedesktop.PolicyKit1.Error.Cancelled` when dismissed);
`CancelAuthentication` closes the dialog.
- `compositor/polkit/helper.mbt`: the PAM conversation through `polkit-agent-helper-1`. With polkit
126+ it connects to `/run/polkit/agent-helper.socket` (socket activation) and sends the user name
and cookie; otherwise it runs the setuid helper (`/usr/lib/polkit-1/...` or
`/usr/libexec/...`) on a socket pair (`sys.spawn-socket`, implemented by all three hosts) and
sends the cookie. On success the helper tells polkitd itself.
- `compositor/polkit/describe.mbt`, `keymap.mbt`, `dialog.mbt`: words for a request, the xkb
keymap parser, the dialog's states. `compositor/host/auth.mbt`: drawing and input.
- Only the login session (`--drm`) registers. The setting is state.edn `:auth-agent :system` when
off. If polkit refuses (another agent already has the session) or there is no system bus, the
compositor starts the third-party agent `chandra-session` found (`CHANDRA_POLKIT_FALLBACK`).
Turning the switch off live unregisters and starts that agent; turning it back on while that
agent runs takes effect at the next login (polkit allows one agent per session).
- Debug: `CHANDRA_POLKIT_HELPER=socket:/path` or `=/path/to/helper` picks the helper.
## Tests
`compositor/polkit/polkit_test.mbt` (keymaps, helper lines, run0 parsing, descriptions, dialog
states) and `compositor/host/auth_test.mbt`, which runs the agent against a mock polkit Authority
on a private `dbus-daemon` and a mock helper on a socket. `CHANDRA_AUTH_SHOTS=/some/dir` writes a
PNG of each dialog state. Not covered by tests: the real polkitd and PAM (registration for a real
logind session, the real helper's socket and setuid paths).
+8 -5
View File
@@ -81,11 +81,14 @@ the password in the terminal, as usual.
### Password prompts without a terminal ### Password prompts without a terminal
Started from a terminal, run0 asks there. Started from the launcher or a keyboard shortcut there is Started from a terminal, run0 asks there. Started from the launcher or a keyboard shortcut there is
no terminal, so run0 and pkexec need a **polkit authentication agent** running in the session. no terminal, so run0 and pkexec need a **polkit authentication agent** in the session. Chandra is
`chandra-session` starts the first one it finds once the compositor is up: polkit-gnome, its own: the compositor registers with polkit and asks in a dialog it draws itself, showing the
mate-polkit, polkit-kde, hyprpolkitagent, xfce-polkit or lxpolkit (install one of them). Set command run0 will run (see [auth-dialog.md](auth-dialog.md)). Turn off Settings → Session →
`CHANDRA_POLKIT_AGENT=/path/to/agent` to choose, or `CHANDRA_POLKIT_AGENT=none` if a systemd "Chandra password dialog" to use a third-party agent instead; `chandra-session` finds the first one
user unit already starts one. Its output goes to the session log. installed (polkit-gnome, mate-polkit, polkit-kde, hyprpolkitagent, xfce-polkit or lxpolkit) and
the compositor starts it then, or whenever polkit won't take Chandra's agent. Set
`CHANDRA_POLKIT_AGENT=/path/to/agent` to always use that agent, or `CHANDRA_POLKIT_AGENT=none` if
a systemd user unit already starts one. Its output goes to the session log.
## Power actions ## Power actions
+43
View File
@@ -993,6 +993,49 @@ impl Host for State {
} }
c.spawn().is_ok() c.spawn().is_ok()
} }
fn spawn_socket(&mut self, argv: String) -> i32 {
use std::os::fd::{FromRawFd, IntoRawFd, OwnedFd};
let args: Vec<&str> = argv.split('\n').filter(|a| !a.is_empty()).collect();
if args.is_empty() || !args[0].starts_with('/') {
return -1;
}
let mut sv = [-1i32; 2];
if unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0, sv.as_mut_ptr()) } != 0 {
return -1;
}
let child_end = unsafe { OwnedFd::from_raw_fd(sv[1]) };
let out = match child_end.try_clone() {
Ok(f) => f,
Err(_) => {
unsafe { libc::close(sv[0]) };
return -1;
}
};
let mut c = Command::new(args[0]);
c.args(&args[1..]).stdin(Stdio::from(child_end)).stdout(Stdio::from(out));
unsafe {
c.pre_exec(|| {
libc::signal(libc::SIGCHLD, libc::SIG_DFL);
libc::signal(libc::SIGPIPE, libc::SIG_DFL);
Ok(())
});
}
match c.spawn() {
Ok(mut child) => {
// Reap it when it exits, so it never lingers as a zombie.
std::thread::spawn(move || {
let _ = child.wait();
});
let fd = unsafe { OwnedFd::from_raw_fd(sv[0]) };
fd.into_raw_fd()
}
Err(_) => {
unsafe { libc::close(sv[0]) };
-1
}
}
}
} }
fn main() -> Result<()> { fn main() -> Result<()> {
+3
View File
@@ -84,6 +84,9 @@ fn wasmImportHasExe(p0 : Int, p1 : Int) -> Int = "chandra:host/sys@0.1.0" "has-e
///| ///|
fn wasmImportSpawn(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "chandra:host/sys@0.1.0" "spawn" fn wasmImportSpawn(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "chandra:host/sys@0.1.0" "spawn"
///|
fn wasmImportSpawnSocket(p0 : Int, p1 : Int) -> Int = "chandra:host/sys@0.1.0" "spawn-socket"
///| ///|
fn wasmImportTakeSigusr1() -> Int = "chandra:host/sys@0.1.0" "take-sigusr1" fn wasmImportTakeSigusr1() -> Int = "chandra:host/sys@0.1.0" "take-sigusr1"
@@ -184,3 +184,8 @@ fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int {
fn mbt_ffi_int_array2ptr(array : FixedArray[Int]) -> Int { fn mbt_ffi_int_array2ptr(array : FixedArray[Int]) -> Int {
abort("wasm-only") abort("wasm-only")
} }
///|
fn wasmImportSpawnSocket(p0 : Int, p1 : Int) -> Int {
abort("wasm-only host import")
}
@@ -42,6 +42,8 @@ pub fn sleep_ms(Int32) -> Unit
pub fn spawn(String, String) -> Bool pub fn spawn(String, String) -> Bool
pub fn spawn_socket(String) -> Int
pub fn take_fd(Int32) -> Int32 pub fn take_fd(Int32) -> Int32
pub fn take_sigusr1() -> Bool pub fn take_sigusr1() -> Bool
+10
View File
@@ -337,3 +337,13 @@ pub fn take_sigusr1() -> Bool {
return ret return ret
} }
///|
pub fn spawn_socket(argv : String) -> Int {
let ptr = mbt_ffi_str2ptr(argv)
let result : Int = wasmImportSpawnSocket(ptr, argv.length());
let ret = result
mbt_ffi_free(ptr)
return ret
}
+10 -16
View File
@@ -130,13 +130,14 @@ if [ -n "$XDG_SESSION_ID" ] && command -v loginctl >/dev/null 2>&1; then
fi fi
fi fi
# A polkit authentication agent, so `chandra-root APP`, run0 and pkexec started from the launcher # Password prompts for `chandra-root APP`, run0 and pkexec started from the launcher or a shortcut
# or a shortcut (no terminal to ask in) can show a password prompt. Uses the first one installed, # (no terminal to ask in): the compositor is its own polkit authentication agent and asks in a
# once the compositor's socket is up (the agents are GTK/Qt apps that need it at startup). # dialog it draws itself (compositor/host/auth.mbt; Settings > Session > "Chandra password
# CHANDRA_POLKIT_AGENT names one explicitly, or "none" to start none (say, when a systemd user # dialog"). When that switch is off, or polkit won't take Chandra's agent, the compositor starts
# unit already starts one). # the first third-party agent installed, found here and passed as CHANDRA_POLKIT_FALLBACK.
agent=${CHANDRA_POLKIT_AGENT:-} # CHANDRA_POLKIT_AGENT=none starts no agent at all (say, when a systemd user unit already starts
if [ -z "$agent" ]; then # one); a path starts that agent instead of Chandra's.
fallback=
for a in \ for a in \
/usr/lib/polkit-gnome/polkit-gnome-authentication-agent-1 \ /usr/lib/polkit-gnome/polkit-gnome-authentication-agent-1 \
/usr/libexec/polkit-gnome-authentication-agent-1 \ /usr/libexec/polkit-gnome-authentication-agent-1 \
@@ -152,16 +153,9 @@ if [ -z "$agent" ]; then
/usr/libexec/xfce-polkit \ /usr/libexec/xfce-polkit \
/usr/lib/xfce-polkit/xfce-polkit \ /usr/lib/xfce-polkit/xfce-polkit \
"$(command -v lxpolkit 2>/dev/null)"; do "$(command -v lxpolkit 2>/dev/null)"; do
if [ -n "$a" ] && [ -x "$a" ]; then agent=$a; break; fi if [ -n "$a" ] && [ -x "$a" ]; then fallback=$a; break; fi
done done
fi export CHANDRA_POLKIT_FALLBACK="$fallback"
if [ -n "$agent" ] && [ "$agent" != none ]; then
(
i=0
while [ ! -S "$sock" ] && [ $i -lt 200 ]; do sleep 0.1; i=$((i + 1)); done
WAYLAND_DISPLAY="$sock" GDK_BACKEND=wayland exec "$agent"
) >>"$log" 2>&1 &
fi
exec "$@" --drm --socket "$sock" \ exec "$@" --drm --socket "$sock" \
--theme "$share/config/themes/moon-night.json" >>"$log" 2>&1 --theme "$share/config/themes/moon-night.json" >>"$log" 2>&1
+4
View File
@@ -208,5 +208,9 @@ fn sys_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] {
"spawn", "spawn",
a => boolean(@sys.spawn(a[0].to_string(), a[1].to_string())), a => boolean(@sys.spawn(a[0].to_string(), a[1].to_string())),
), ),
(
"spawn-socket",
a => s32(@sys.spawn_socket(a[0].to_string().split("\n").map(v => v.to_string()).to_array())),
),
] ]
} }
+4
View File
@@ -66,6 +66,10 @@ interface sys {
has-exe: func(name: string) -> bool; has-exe: func(name: string) -> bool;
/// Launch `cmd` detached with WAYLAND_DISPLAY set to `display`. /// Launch `cmd` detached with WAYLAND_DISPLAY set to `display`.
spawn: func(cmd: string, display: string) -> bool; spawn: func(cmd: string, display: string) -> bool;
/// Run a program with its stdin and stdout on one end of a socket pair; our end, or -1.
/// `argv` is the absolute program path then its arguments, separated by newlines. Its stderr
/// is the host's. Not waited for. Used for polkit's setuid authentication helper.
spawn-socket: func(argv: string) -> s32;
/// True once after the host process got SIGUSR1 (a request to reload the panel modules from /// True once after the host process got SIGUSR1 (a request to reload the panel modules from
/// disk; see docs/reloading.md). The first call installs the handler; until then SIGUSR1 keeps /// disk; see docs/reloading.md). The first call installs the handler; until then SIGUSR1 keeps
/// its default action. A signal interrupts `wait-readable`, so an idle loop wakes for it. /// its default action. A signal interrupts `wait-readable`, so an idle loop wakes for it.