Password dialog: Chandra is its own polkit agent, drawn in the shell layer
CI / test (push) Failing after 18s
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:
32 files changed
+3930
-43
No files matched your search
@@ -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)
|
||||
})
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -145,6 +145,23 @@ pub(all) struct ChandraCompositor {
|
||||
mut rec_pointer : Bool
|
||||
mut rec_press : Bool
|
||||
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,
|
||||
dark_theme: theme,
|
||||
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,
|
||||
control: None,
|
||||
login_session: false,
|
||||
@@ -283,6 +311,11 @@ pub fn ChandraCompositor::close(self : ChandraCompositor) -> Unit {
|
||||
release_snapshot(win.surface)
|
||||
}
|
||||
self.stop_control()
|
||||
self.close_auth(Some(Err("The session is ending")))
|
||||
match self.polkit {
|
||||
Some(a) => a.stop()
|
||||
None => ()
|
||||
}
|
||||
self.shell.shutdown()
|
||||
match self.settings_portal {
|
||||
Some(p) => p.close()
|
||||
@@ -389,6 +422,7 @@ fn ChandraCompositor::flush_configures(self : ChandraCompositor) -> Unit {
|
||||
pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit {
|
||||
self.flush_configures()
|
||||
self.portal_tick()
|
||||
self.auth_tick()
|
||||
self.control_tick()
|
||||
let events = self.server.poll_events()
|
||||
for ev in events {
|
||||
@@ -598,6 +632,7 @@ pub fn ChandraCompositor::has_timed_work(self : ChandraCompositor) -> Bool {
|
||||
self.shot_request is Some(_) ||
|
||||
self.rec_request is Some(_) ||
|
||||
self.shot_toast is Some(_) ||
|
||||
self.auth_animating() ||
|
||||
self.thumbs_pending() ||
|
||||
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 {
|
||||
Some(snap) => scene.popups.push((self.popup_rect(p), snap))
|
||||
None => ()
|
||||
@@ -729,6 +765,7 @@ fn ChandraCompositor::build_scene(
|
||||
panel_ops.append(self.switcher_ops())
|
||||
}
|
||||
panel_ops.append(self.screenshot_ops())
|
||||
panel_ops.append(self.auth_ops())
|
||||
self.frames_built = self.frames_built + 1
|
||||
self.run_shell_actions()
|
||||
// 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::Logout => self.quit_requested = true
|
||||
@shell.ShellAction::ThemeChanged => self.apply_theme()
|
||||
@shell.ShellAction::AuthAgentChanged => self.auth_agent_setting_changed()
|
||||
@shell.ShellAction::Screenshot(code) => self.screenshot_request(code)
|
||||
@shell.ShellAction::SystemPower(a) => self.system_power(a)
|
||||
@shell.ShellAction::Window(wid, cmd) => self.window_command(wid, cmd)
|
||||
@@ -1292,6 +1330,21 @@ pub fn ChandraCompositor::handle_input(
|
||||
time_ms : UInt,
|
||||
) -> Unit {
|
||||
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 {
|
||||
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
|
||||
/// decides over the launcher; a client window decides inside its client area; otherwise default.
|
||||
pub fn ChandraCompositor::desired_cursor(self : ChandraCompositor) -> UInt {
|
||||
match self.auth {
|
||||
Some(ui) => return self.auth_cursor(ui)
|
||||
None => ()
|
||||
}
|
||||
match self.shot {
|
||||
Some(o) => return self.overlay_cursor(o)
|
||||
None => ()
|
||||
|
||||
@@ -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_true(comp.shell.open_settings(Session))
|
||||
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
|
||||
}
|
||||
|
||||
///|
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
"chandra/desktop/compositor/gfx" @gfx,
|
||||
"chandra/desktop/compositor/network" @network,
|
||||
"chandra/desktop/compositor/portal" @portal,
|
||||
"chandra/desktop/compositor/polkit" @polkit,
|
||||
}
|
||||
|
||||
supported_targets = "+native+wasm"
|
||||
|
||||
Reference in new issue
Block a user