///| 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 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 `/.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") // Face unlock (pam_chandra_face.so): the face row scans, then gives way to the password. helper_say(h2, "PAM_TEXT_INFO Face unlock: looking for ada…") assert_true(settle(comp, a, fn() { comp.auth_dialog().map(d => d.face == Scanning).unwrap_or(false) })) assert_eq(comp.auth_dialog().unwrap().info, "") // the fingerprint message went with nandi's attempt auth_shot(comp, "14-face-scanning") helper_say(h2, "PAM_ERROR_MSG Face unlock: face not recognized") 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) })) assert_eq(comp.auth_dialog().unwrap().face, FaceFailed("Face not recognized")) auth_shot(comp, "15-face-failed") 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() }