Files
chandra/compositor/host/auth_test.mbt
T
nandi c790f96e58
CI / test (push) Failing after 52s
Lock: add session lock from power button and chandra-ctl lock
- Lock the session from the power button or `chandra-ctl lock`
- Unlock with a face or the password; the password always works
- Add compositor lock module with tests, and a polkit unlock policy (org.chandra.unlock)
- Document the lock flow in docs/lock.md and link it from the README
- Add generated interface bindings for the compositor and widget components
2026-11-29 03:24:46 -08:00

1068 lines
39 KiB
MoonBit

///| Chandra's password dialog end to end: the compositor, chandra-polkit-agent's loop (run
/// in-process on a socket pair, and as the real program), 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. Also handles CheckAuthorization /
/// CancelCheckAuthorization for org.chandra.unlock using `unix-process`.
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]
/// Subjects passed to CheckAuthorization.
check_subjects : Array[@network.DValue]
/// Cancel ids passed to CancelCheckAuthorization.
cancelled_ids : Array[String]
/// Monotonic cookie counter for CheckAuthorization -> BeginAuthentication.
mut check_seq : Int
/// In-flight CheckAuthorization calls: (cookie, cancel_id, call_msg).
pending_checks : Array[(String, String, @network.DMessage)]
}
///|
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: [],
check_subjects: [],
cancelled_ids: [],
check_seq: 0,
pending_checks: [],
}
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, [])
"CheckAuthorization" =>
match m.body {
[Struct([Str("unix-process"), Arr(_, _)]) as subj, Str(action_id), _, U32(_), Str(cancel_id)] => {
a.check_subjects.push(subj)
a.check_seq = a.check_seq + 1
let cookie = "unlock-cookie-" + a.check_seq.to_string()
a.pending_checks.push((cookie, cancel_id, m))
let ids : Array[@network.DValue] = [
Struct([
Str("unix-user"),
@network.dict("v", [("uid", Variant(U32(@polkit.own_uid().reinterpret_as_uint())))]),
]),
]
ignore(
bus.call(
@network.DMessage::call(a.agent, @polkit.agent_path, @polkit.agent_iface, "BeginAuthentication", [
Str(action_id),
Str("Authentication is required to unlock the screen"),
Str(""),
@network.DValue::Arr("{ss}", []),
Str(cookie),
Arr("(sa{sv})", ids),
]),
on_reply=fn(rm) {
let ok = rm.mtype == @network.method_return
a.answers.push(if ok { "ok" } else { rm.error_name })
match a.pending_checks.search_by(c => c.0 == cookie) {
Some(idx) => {
let (_, _, req_msg) = a.pending_checks.remove(idx)
bus.reply(req_msg, [Struct([Bool(ok), Bool(false), @network.dict("s", [])])])
}
None => ()
}
},
),
)
}
_ => bus.reply_error(m, "org.freedesktop.DBus.Error.InvalidArgs", "bad CheckAuthorization args")
}
"CancelCheckAuthorization" =>
match m.body {
[Str(cancel_id)] => {
a.cancelled_ids.push(cancel_id)
match a.pending_checks.search_by(c => c.1 == cancel_id) {
Some(idx) => {
let (cookie, _, req_msg) = a.pending_checks.remove(idx)
ignore(
bus.call(
@network.DMessage::call(a.agent, @polkit.agent_path, @polkit.agent_iface, "CancelAuthentication", [
Str(cookie),
]),
on_reply=fn(_) { () },
),
)
bus.reply(req_msg, [Struct([Bool(false), Bool(false), @network.dict("s", [])])])
}
None => ()
}
bus.reply(m, [])
}
_ => bus.reply_error(m, "org.freedesktop.DBus.Error.InvalidArgs", "bad CancelCheckAuthorization args")
}
_ => 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)], uid? : UInt = 1000) -> Unit {
let ids : Array[@network.DValue] = [
Struct([Str("unix-user"), @network.dict("v", [("uid", Variant(U32(uid)))])]),
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 connected pair of stream sockets: (the compositor's end, the agent's end).
fn sock_pair(tag : String) -> (Int, Int) {
let path = "/tmp/chandra-auth-link-" + tag + "-" + @sys.getpid().to_string()
@sys.unlink(path)
let l = @sys.unix_listen(path)
let c = @sys.unix_connect(path)
let mut s = -1
for i = 0; i < 100 && s < 0; i = i + 1 {
s = @sys.unix_accept(l)
if s < 0 {
@sys.sleep_ms(5)
}
}
@sys.close_fd(l)
@sys.unlink(path)
(c, s)
}
///| A compositor, the mock polkitd (when there is a bus), and the agents it started in-process.
struct Rig {
comp : @host.ChandraCompositor
a : MockAuthority?
agents : Array[@polkit.AgentLoop]
}
///| A compositor whose agents run in this process: the session's on `bus` with the helper at
/// `helper` (a socket the test listens on), demos as `chandra-ctl auth-demo` starts them.
fn rig(tag : String, bus : String?, helper : String) -> Rig {
let comp = new_comp("auth-" + tag)
comp.login_session = true
let a = bus.map(b => MockAuthority::new(b))
let agents : Array[@polkit.AgentLoop] = []
let n : Ref[Int] = { val: 0 }
comp.auth_spawner = Some(fn(args) {
n.val = n.val + 1
let (mine, theirs) = sock_pair(tag + "-" + n.val.to_string())
let ag = match args {
["--demo", mode] => @polkit.AgentLoop::new_demo(theirs, mode)
_ => {
let subject = @network.DValue::Struct([Str("unix-session"), @network.dict("v", [("session-id", Variant(Str("2")))])])
@polkit.AgentLoop::new(
theirs,
@polkit.PolkitAgent::new(bus_path=bus.unwrap_or("/nonexistent/bus"), subject~, make_request=fake_request),
routes=[Socket(helper)],
describer=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",
)
},
)
}
}
ag.start()
agents.push(ag)
mine
})
{ comp, a, agents }
}
///| One pass of everything: polkitd, the agents, the compositor.
fn Rig::pass(self : Rig) -> Unit {
match self.a {
Some(a) => a.bus.pump()
None => ()
}
for ag in self.agents {
if !ag.finished() {
ag.step()
}
}
self.comp.step()
}
///| Run everything until `cond` holds (or about six seconds pass).
fn Rig::settle(self : Rig, cond : () -> Bool) -> Bool {
for i = 0; i < 600; i = i + 1 {
self.pass()
if cond() {
return true
}
@sys.sleep_ms(10)
}
false
}
///| The session's agent registered with polkit.
fn Rig::ready(self : Rig) -> Bool {
self.comp.auth_agent.map(l => l.ready).unwrap_or(false)
}
///| The mock polkitd.
fn Rig::authority(self : Rig) -> MockAuthority {
self.a.unwrap()
}
///| The dialog's view (aborts when none is up).
fn Rig::view(self : Rig) -> @polkit.AuthView {
self.comp.auth_view().unwrap()
}
///| The mock helper's side of one check: accept, read the user and cookie lines.
fn Rig::helper_accept(self : Rig, listen : Int) -> (Int, String) {
let fd : Ref[Int] = { val: -1 }
ignore(self.settle(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 (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)
}
///| Alt+key.
fn auth_alt(comp : @host.ChandraCompositor, code : UInt) -> Unit {
comp.handle_input(@nested.InputEvent::Modifiers(8U, 0U, 0U, 0U), 1U)
auth_press(comp, code)
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 1U)
}
///| Click the dialog's control `f`.
fn auth_click(comp : @host.ChandraCompositor, f : @polkit.Focus) -> Unit {
ignore(comp.compose_frame())
let r = comp.auth.unwrap().hits.filter(x => x.1 == f)[0].0
comp.handle_input(@nested.InputEvent::PointerMove((r.x + 4).to_double(), (r.y + 4).to_double()), 1U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, true), 2U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 3U)
}
///| 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_view() {
Some(v) => v.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"),
]
///| A private bus and a listening mock helper socket for test `tag`.
fn helper_socket(tag : String) -> (String, Int) {
let hpath = "/tmp/chandra-auth-helper-" + tag + "-" + @sys.getpid().to_string()
@sys.unlink(hpath)
(hpath, @sys.unix_listen(hpath))
}
///|
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 (hpath, listen) = helper_socket("ok")
let r = rig("ok", Some(bus), hpath)
r.comp.start_auth_agent()
assert_true(r.settle(fn() { r.ready() }))
let a = r.authority()
assert_true(a.agent != "")
a.begin("cookie-1", run0_details)
assert_true(r.settle(fn() { r.comp.auth_view() is Some(_) }))
let d = r.view()
assert_eq(d.title, "Run a command as root")
assert_eq(d.command, "gparted /dev/nvme0n1")
// The user at the screen comes first; the wheel group adds ada.
assert_eq(d.users.map(u => u.name), ["nandi", "ada"])
// The helper is asked for nandi with polkit's cookie.
let (h, hello) = r.helper_accept(listen)
assert_eq(hello, "nandi|cookie-1")
auth_shot(r.comp, "01-starting")
helper_say(h, "PAM_PROMPT_ECHO_OFF Password: ")
assert_true(r.settle(fn() { d.phase == Asking }))
auth_shot(r.comp, "02-idle")
auth_type(r.comp, "Hunter2")
assert_eq(d.typed(), 7)
auth_shot(r.comp, "03-typing")
// Caps Lock on shows a warning.
r.comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 2U, 0U), 1U)
assert_true(d.caps)
auth_shot(r.comp, "04-caps-lock")
r.comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 1U)
auth_press(r.comp, 28U) // Enter
assert_eq(d.typed(), 0) // wiped once sent
assert_true(r.settle(fn() { d.phase == Checking }))
assert_eq(helper_lines(h, 1), "Hunter2")
auth_shot(r.comp, "05-busy")
// Wrong: the helper fails and exits; the dialog shakes, says so, and a new check starts.
helper_say(h, "FAILURE")
@sys.close_fd(h)
assert_true(r.settle(fn() { d.failures == 1 }))
assert_eq(d.error, "Wrong password. Try again.")
assert_true(d.shake_at != 0UL)
let (h2, hello2) = r.helper_accept(listen)
assert_eq(hello2, "nandi|cookie-1")
helper_say(h2, "PAM_PROMPT_ECHO_OFF Password: ")
assert_true(r.settle(fn() { d.phase == Asking }))
auth_shot(r.comp, "06-wrong-password")
// Details, then the right password.
auth_alt(r.comp, 32U) // Alt+D
assert_true(d.details_open)
auth_type(r.comp, "hunter2")
auth_shot(r.comp, "07-details")
auth_alt(r.comp, 19U) // Alt+R: show it
assert_true(d.reveal)
auth_shot(r.comp, "08-revealed")
r.comp.theme = @scene.ThemeTokens::moon_day()
auth_shot(r.comp, "09-light")
auth_alt(r.comp, 19U)
auth_press(r.comp, 32U) // Alt is up: 'd' goes into the field
auth_press(r.comp, 14U) // and Backspace takes it out
auth_shot(r.comp, "10-light-details")
auth_press(r.comp, 96U) // keypad Enter
assert_true(r.settle(fn() { d.phase == Checking }))
assert_eq(helper_lines(h2, 1), "hunter2")
helper_say(h2, "SUCCESS")
assert_true(r.settle(fn() { r.comp.auth_view() is None && 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(r.comp.auth_swallow.length(), 0)
assert_true(r.comp.auth_notice_text() is None)
@sys.close_fd(h2)
@sys.close_fd(listen)
@sys.unlink(hpath)
r.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 (hpath, listen) = helper_socket("cancel")
let r = rig("cancel", Some(bus), hpath)
r.comp.start_auth_agent()
assert_true(r.settle(fn() { r.ready() }))
let a = r.authority()
a.begin("c1", run0_details)
a.begin("c2", [])
assert_true(r.settle(fn() { r.comp.auth_view() is Some(_) }))
let (h, _) = r.helper_accept(listen)
// A fingerprint reader: PAM informs and waits.
helper_say(h, "PAM_TEXT_INFO Place your finger on the fingerprint reader")
assert_true(r.settle(fn() { r.view().info != "" }))
assert_eq(r.view().phase, Starting)
auth_shot(r.comp, "11-fingerprint")
// Two accounts can answer: Tab to the picker, Right picks ada and starts a check for her.
auth_press(r.comp, 15U)
auth_press(r.comp, 106U)
let (h2, hello) = r.helper_accept(listen)
assert_eq(hello, "ada|c1")
assert_true(r.settle(fn() { r.view().user().map(u => u.name) == Some("ada") }))
// 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(r.settle(fn() { r.view().face == Scanning }))
assert_eq(r.view().info, "") // the fingerprint message went with nandi's attempt
auth_shot(r.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(r.settle(fn() { r.view().phase == Asking }))
assert_eq(r.view().face, FaceFailed("Face not recognized"))
auth_shot(r.comp, "15-face-failed")
auth_shot(r.comp, "12-other-account")
auth_press(r.comp, 1U) // Escape
assert_true(r.comp.auth_view() is None || r.view().id != "1")
assert_true(r.settle(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(r.settle(fn() { r.comp.auth_view().map(v => v.id == "2").unwrap_or(false) }))
assert_eq(r.view().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(r.settle(fn() { r.comp.auth_view() is None }))
assert_true(r.settle(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)
r.comp.close()
}
///|
test "polkit refuses the agent: a notice says why, and no other agent takes over" {
let bus = match auth_bus("refuse") {
Some(b) => b
None => return
}
let r = rig("refuse", Some(bus), "/nonexistent")
r.authority().refuse = "An authentication agent already exists for the given subject"
r.comp.start_auth_agent()
assert_true(r.settle(fn() { r.comp.auth_notice_text() is Some(_) }))
assert_eq(
r.comp.auth_notice_text().unwrap(),
"Chandra's password dialog couldn't start: polkit refused the agent: An authentication agent already exists for the given subject.",
)
assert_true(r.comp.auth_agent is None)
assert_false(r.comp.fallback_agent_started)
let (out, ok) = r.comp.control_command("auth-status")
assert_true(ok)
assert_eq(out[0], "agent: not running")
auth_shot(r.comp, "16-notice")
// A click on it dismisses it.
ignore(r.comp.compose_frame())
r.comp.handle_input(@nested.InputEvent::PointerMove(640.0, 40.0), 1U)
r.comp.handle_input(@nested.InputEvent::PointerButton(272U, true), 2U)
r.comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 3U)
assert_true(r.comp.auth_notice_text() is None)
r.comp.close()
}
///|
test "the agent can't be started, or quits at start: a notice says so" {
// No program to run.
let r = rig("nostart", None, "")
r.comp.auth_spawner = Some(fn(_) { -1 })
r.comp.start_auth_agent()
assert_eq(r.comp.auth_notice_text(), Some("Chandra's password dialog couldn't start: could not run chandra-polkit-agent."))
r.comp.close()
// Started, but polkit can't even be asked (no system bus): its error is the notice.
let r2 = rig("nobus", None, "")
r2.comp.start_auth_agent()
assert_true(r2.settle(fn() { r2.comp.auth_notice_text() is Some(_) }))
assert_true(r2.comp.auth_notice_text().unwrap().has_prefix("Chandra's password dialog couldn't start: polkit could not be asked: no system bus at /nonexistent/bus"))
r2.comp.close()
// It crashes before saying anything.
let r3 = rig("crash", None, "")
r3.comp.auth_spawner = Some(fn(_) {
let (mine, theirs) = sock_pair("crash")
@sys.close_fd(theirs)
mine
})
r3.comp.start_auth_agent()
assert_true(r3.settle(fn() { r3.comp.auth_notice_text() is Some(_) }))
assert_eq(
r3.comp.auth_notice_text().unwrap(),
"Chandra's password dialog couldn't start: chandra-polkit-agent stopped unexpectedly (see ~/.local/state/chandra/session.log).",
)
r3.comp.close()
}
///|
test "the agent stops after it was registered: it is started again, and a notice says so" {
let bus = match auth_bus("restart") {
Some(b) => b
None => return
}
let r = rig("restart", Some(bus), "/nonexistent")
r.comp.start_auth_agent()
assert_true(r.settle(fn() { r.ready() }))
let first = r.agents[0]
first.shutdown() // as if it crashed: its end of the link closes
assert_true(r.settle(fn() { r.comp.auth_notice_text() is Some(_) }))
assert_true(r.comp.auth_notice_text().unwrap().has_prefix("Chandra's password dialog stopped and was restarted"))
assert_true(r.settle(fn() { r.ready() }))
assert_eq(r.agents.length(), 2)
r.comp.close()
}
///|
test "polkit's helper can't be reached: the dialog says why and waits; Try again, then Cancel" {
let bus = match auth_bus("nohelper") {
Some(b) => b
None => return
}
let r = rig("nohelper", Some(bus), "/nonexistent/helper.socket")
r.comp.start_auth_agent()
assert_true(r.settle(fn() { r.ready() }))
let a = r.authority()
a.begin("c1", run0_details)
assert_true(r.settle(fn() { r.comp.auth_view() is Some(_) }))
let d = r.view()
assert_eq(d.phase, Failed)
assert_eq(d.error, "polkit's password checker could not be started (tried socket /nonexistent/helper.socket)")
assert_eq(d.main_label(), "Try again")
auth_shot(r.comp, "17-failed")
// Enter tries again (and says the same).
auth_press(r.comp, 28U)
assert_true(r.settle(fn() { d.phase == Failed }))
// Clicking Cancel dismisses it.
auth_click(r.comp, Cancel)
assert_true(r.comp.auth_view() is None)
assert_true(r.settle(fn() { a.answers.length() == 1 }))
r.comp.close()
}
///|
test "typing reaches the dialog through handle_input on a real keymap; a check that quits early is not retried behind the user's back" {
let bus = match auth_bus("typing") {
Some(b) => b
None => return
}
let (hpath, listen) = helper_socket("typing")
let r = rig("typing", Some(bus), hpath)
// The keymap the real session hands clients (xkbcommon's text format), not the US fallback.
r.comp.server.set_keymap(@utf8.encode(real_keymap))
r.comp.start_auth_agent()
assert_true(r.settle(fn() { r.ready() }))
let a = r.authority()
a.begin("t1", run0_details)
assert_true(r.settle(fn() { r.comp.auth_view() is Some(_) }))
let d = r.view()
// The helper goes away without a word (socket helper refusing, account locked, ...).
let (h, _) = r.helper_accept(listen)
@sys.close_fd(h)
assert_true(r.settle(fn() { d.phase == Failed }))
assert_eq(d.error, "The password check quit before asking for a password.")
assert_eq(d.failures, 0) // not a wrong password
// Nothing starts another check on its own.
for i = 0; i < 30; i = i + 1 {
r.pass()
@sys.sleep_ms(10)
}
assert_true(@sys.unix_accept(listen) < 0)
// Typing lands in the field and stays there.
auth_type(r.comp, "Secret9")
assert_eq(d.typed(), 7)
// Shift+digit through the real keymap: '(' on 9.
r.comp.handle_input(@nested.InputEvent::Modifiers(1U, 0U, 0U, 0U), 1U)
auth_press(r.comp, 10U)
r.comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 1U)
assert_eq(d.typed(), 8)
// Enter starts a new check, which gets the password when it asks.
auth_press(r.comp, 28U)
let (h2, hello) = r.helper_accept(listen)
assert_eq(hello, "nandi|t1")
helper_say(h2, "PAM_PROMPT_ECHO_OFF Password: ")
assert_true(r.settle(fn() { d.phase == Checking }))
assert_eq(helper_lines(h2, 1), "Secret9(")
helper_say(h2, "SUCCESS")
assert_true(r.settle(fn() { a.answers == ["ok"] }))
@sys.close_fd(h2)
@sys.close_fd(listen)
@sys.unlink(hpath)
r.comp.close()
}
///|
test "chandra-ctl auth-demo: the dialog without root; wrong, then the demo password" {
let r = rig("demo", None, "")
let (out, ok) = r.comp.control_command("auth-demo")
assert_true(ok)
assert_eq(out, ["ok the demo dialog opens; the password is \"demo\""])
assert_true(r.settle(fn() { r.comp.auth_view().map(v => v.phase == Asking).unwrap_or(false) }))
let d = r.view()
assert_eq(d.command, "run0 systemctl restart chandra-demo.service")
auth_type(r.comp, "nope")
auth_press(r.comp, 28U)
assert_true(r.settle(fn() { d.failures == 1 }))
assert_eq(d.error, "Wrong password. Try again.")
assert_true(r.settle(fn() { d.phase == Asking }))
auth_type(r.comp, "demo")
auth_click(r.comp, Allow)
assert_true(r.settle(fn() { r.comp.auth_view() is None && r.comp.auth_demos.length() == 0 }))
assert_true(r.comp.auth_notice_text() is None)
assert_eq(r.comp.control_command("auth-demo bogus").1, false)
r.comp.close()
}
///|
test "auth-demo die and face: a check that quits shows why until Try again; the face row" {
let r = rig("demo-die", None, "")
ignore(r.comp.control_command("auth-demo die"))
assert_true(r.settle(fn() { r.comp.auth_view().map(v => v.phase == Failed).unwrap_or(false) }))
let d = r.view()
assert_eq(d.error, "The password check quit before asking for a password.")
auth_click(r.comp, Allow) // "Try again"
assert_true(r.settle(fn() { d.phase == Asking }))
assert_eq(d.error, "")
auth_press(r.comp, 1U) // Escape
assert_true(r.settle(fn() { r.comp.auth_demos.length() == 0 }))
ignore(r.comp.control_command("auth-demo face"))
assert_true(r.settle(fn() { r.comp.auth_view().map(v => v.face == Scanning).unwrap_or(false) }))
// Typed while it looks: goes in when PAM asks.
auth_type(r.comp, "demo")
auth_press(r.comp, 28U)
assert_true(r.settle(fn() { r.comp.auth_view() is None && r.comp.auth_demos.length() == 0 }))
r.comp.close()
}
///| The agent program the build made (release or debug), "" when it wasn't built.
fn built_agent() -> String {
for p in ["_build/native/release/build/compositor/authagent/authagent.exe", "_build/native/debug/build/compositor/authagent/authagent.exe"] {
if @sys.has_exe(p) {
return p
}
}
""
}
///| Run everything with the agent out of process: polkitd and the compositor.
fn settle_out(comp : @host.ChandraCompositor, a : MockAuthority?, cond : () -> Bool) -> Bool {
for i = 0; i < 500; i = i + 1 {
match a {
Some(a) => a.bus.pump()
None => ()
}
ignore(@sys.wait_readable(comp.auth_fds(), 10))
comp.step()
if cond() {
return true
}
}
false
}
///|
test "the real chandra-polkit-agent program: demo, and registered with (mock) polkit through its own process" {
let bin = built_agent()
if bin == "" {
println("skipped: build compositor/authagent first (just auth-agent)")
return
}
// The demo, started by the compositor itself through spawn_socket.
let comp = new_comp("auth-real-demo")
assert_true(comp.start_auth_demo("password") is Ok(_))
assert_true(settle_out(comp, None, fn() { comp.auth_view().map(v => v.phase == Asking).unwrap_or(false) }))
auth_type(comp, "demo")
auth_press(comp, 28U)
assert_true(settle_out(comp, None, fn() { comp.auth_view() is None && comp.auth_demos.length() == 0 }))
comp.close()
// The session agent: the system bus, session and helper socket point at the test's mocks.
let bus = match auth_bus("real") {
Some(b) => b
None => return
}
let a = MockAuthority::new(bus)
let (hpath, listen) = helper_socket("real")
let comp2 = new_comp("auth-real")
comp2.login_session = true
comp2.auth_spawner = Some(fn(args) {
@sys.spawn_socket(
[
"/usr/bin/env", "DBUS_SYSTEM_BUS_ADDRESS=unix:path=" + bus, "XDG_SESSION_ID=2", "CHANDRA_POLKIT_HELPER=socket:" + hpath,
bin, ..args,
],
)
})
comp2.start_auth_agent()
assert_true(settle_out(comp2, Some(a), fn() { comp2.auth_agent.map(l => l.ready).unwrap_or(false) }))
a.begin("r1", run0_details, uid=@polkit.own_uid().reinterpret_as_uint())
assert_true(settle_out(comp2, Some(a), fn() { comp2.auth_view() is Some(_) }))
let fd : Ref[Int] = { val: -1 }
assert_true(settle_out(comp2, Some(a), fn() {
if fd.val < 0 {
fd.val = @sys.unix_accept(listen)
}
fd.val >= 0
}))
ignore(helper_lines(fd.val, 2))
helper_say(fd.val, "PAM_PROMPT_ECHO_OFF Password: ")
assert_true(settle_out(comp2, Some(a), fn() { comp2.auth_view().map(v => v.phase == Asking).unwrap_or(false) }))
auth_type(comp2, "Right1")
auth_press(comp2, 28U)
assert_true(settle_out(comp2, Some(a), fn() { comp2.auth_view().map(v => v.phase == Checking).unwrap_or(false) }))
assert_eq(helper_lines(fd.val, 1), "Right1")
helper_say(fd.val, "SUCCESS")
assert_true(settle_out(comp2, Some(a), fn() { a.answers == ["ok"] }))
// Turning the switch off stops it (it unregisters and exits) and says there's no other agent.
comp2.shell.set_session_setting(3, false)
comp2.auth_agent_setting_changed()
assert_true(comp2.auth_agent is None)
@sys.close_fd(fd.val)
@sys.close_fd(listen)
@sys.unlink(hpath)
comp2.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()
}
///| An xkbcommon 1.6 keymap (xkbcli compile-keymap --layout us), cut down to what typing needs.
let real_keymap : String =
#|xkb_keymap {
#|xkb_keycodes "(unnamed)" {
#| minimum = 8;
#| maximum = 708;
#| <ESC> = 9;
#| <AE01> = 10;
#| <AE02> = 11;
#| <AE09> = 18;
#| <AE10> = 19;
#| <AD01> = 24;
#| <AD02> = 25;
#| <AD03> = 26;
#| <AD04> = 27;
#| <AD05> = 28;
#| <AC01> = 38;
#| <AC02> = 39;
#| <AB03> = 54;
#| <AB07> = 58;
#| <AB06> = 57;
#| <SPCE> = 65;
#| indicator 1 = "Caps Lock";
#| alias <AC12> = <BKSL>;
#|};
#|
#|xkb_types "(unnamed)" {
#| virtual_modifiers NumLock,Alt,LevelThree,LevelFive,Meta,Super,Hyper,ScrollLock;
#| type "ONE_LEVEL" {
#| modifiers= none;
#| level_name[1]= "Any";
#| };
#| type "ALPHABETIC" {
#| modifiers= Shift+Lock;
#| map[Shift]= 2;
#| map[Lock]= 2;
#| level_name[1]= "Base";
#| level_name[2]= "Caps";
#| };
#|};
#|
#|xkb_compatibility "(unnamed)" {
#| virtual_modifiers NumLock,Alt,LevelThree,LevelFive,Meta,Super,Hyper,ScrollLock;
#| interpret.useModMapMods= AnyLevel;
#| interpret Shift_L+AnyOf(all) {
#| action= SetMods(modifiers=Shift,clearLocks);
#| };
#| indicator "Caps Lock" {
#| whichModState= locked;
#| modifiers= Lock;
#| };
#|};
#|
#|xkb_symbols "(unnamed)" {
#| name[Group1]="English (US)";
#|
#| key <ESC> { [ Escape ] };
#| key <AE01> { [ 1, exclam ] };
#| key <AE02> { [ 2, at ] };
#| key <AE09> { [ 9, parenleft ] };
#| key <AE10> { [ 0, parenright ] };
#| key <AD01> { [ q, Q ] };
#| key <AD02> { [ w, W ] };
#| key <AD03> { [ e, E ] };
#| key <AD04> { [ r, R ] };
#| key <AD05> { [ t, T ] };
#| key <AC01> { [ a, A ] };
#| key <AC02> { [ s, S ] };
#| key <AB03> { [ c, C ] };
#| key <AB06> { [ n, N ] };
#| key <AB07> { [ m, M ] };
#| key <SPCE> { [ space ] };
#| modifier_map Shift { <LFSH>, <RTSH> };
#| modifier_map Lock { <CAPS> };
#|};
#|
#|};
///|
test "Face unlock window: snaps, Apply, then the password dialog gets the keyboard and the click" {
let bus = match auth_bus("faceapply") {
Some(b) => b
None => return
}
let (hpath, listen) = helper_socket("faceapply")
let r = rig("faceapply", Some(bus), hpath)
let comp = r.comp
comp.server.set_keymap(@utf8.encode(real_keymap))
comp.start_auth_agent()
let fsettle = fn(cond : () -> Bool) {
r.settle(fn() {
ignore(comp.compose_frame())
cond()
})
}
assert_true(fsettle(fn() { r.ready() }))
let a = r.authority()
let dir = "/tmp/chandra-face-apply-" + @sys.getpid().to_string()
let tool = fake_face_tool(dir)
ignore(@sys.write_file_bytes(dir + "/wait", b""))
comp.shell.set_face_tool(["/bin/sh", tool])
assert_true(comp.shell.open_settings(Session))
assert_true(fsettle(fn() { face_texts(comp).contains("Desk") }))
face_click(comp, "Add or remove faces…", 10U)
assert_true(fsettle(fn() { comp.shell.face.window.map(w => w.picture != 0U).unwrap_or(false) }))
let w = comp.shell.face.window.unwrap()
face_key(comp, 57U, 20U)
assert_true(fsettle(fn() { w.snaps.length() == 1 }))
face_key(comp, 57U, 30U)
assert_true(fsettle(fn() { w.snaps.length() == 2 }))
// Enter: Apply; the root step asks polkit, which asks us. Meanwhile the window steps aside.
face_key(comp, 28U, 40U)
assert_true(w.applying)
ignore(comp.compose_frame())
comp.handle_input(@nested.InputEvent::Key(57U, true), 1U)
comp.handle_input(@nested.InputEvent::Key(57U, false), 1U)
assert_eq(w.snaps.length(), 2)
a.begin("f1", run0_details)
assert_true(fsettle(fn() { comp.auth_view() is Some(_) }))
let d = r.view()
let (h, _) = r.helper_accept(listen)
helper_say(h, "PAM_PROMPT_ECHO_OFF Password: ")
assert_true(fsettle(fn() { d.phase == Asking }))
auth_shot(comp, "18-face-apply-password")
// Typing goes to the password dialog, not to the window under it (Space would snap).
auth_type(comp, "Secret9")
comp.handle_input(@nested.InputEvent::Key(57U, true), 1U)
comp.handle_input(@nested.InputEvent::Key(57U, false), 1U)
assert_eq(d.typed(), 8)
assert_eq(w.snaps.length(), 2)
// The Authenticate button takes the click.
auth_click(comp, Allow)
assert_true(fsettle(fn() { d.phase == Checking }))
assert_eq(helper_lines(h, 1), "Secret9 ")
helper_say(h, "SUCCESS")
assert_true(fsettle(fn() { comp.auth_view() is None && a.answers.length() == 1 }))
// The root step goes on; the window closes with what it said.
ignore(@sys.write_file_bytes(dir + "/go", b""))
assert_true(fsettle(fn() { comp.shell.face.window is None }))
assert_eq(comp.shell.face.message, "Added Face 2 and removed 1 face")
@sys.close_fd(h)
@sys.close_fd(listen)
@sys.unlink(hpath)
comp.close()
}
///|
test "hex-keysym keymap, OSK auto-open/reopen, touch OSK tap, and remote_commit_text type into the password dialog" {
let hex_keymap : String =
#|xkb_keymap {
#|xkb_keycodes "evdev_aliases(qwerty)" {
#| minimum = 8;
#| maximum = 255;
#| <ESC> = 9;
#| <BKSP> = 22;
#| <AD03> = 26;
#| <AD04> = 27;
#| <AD09> = 32;
#| <RTRN> = 36;
#| <AC03> = 40;
#| <AB07> = 58;
#| <SPCE> = 65;
#|};
#|xkb_symbols "pc_us_inet(evdev)" {
#| key <ESC> { [ 0xff1b ] };
#| key <BKSP> { [ 0xff08, 0xff08 ] };
#| key <AD03> { [ 0x65, 0x45 ] };
#| key <AD04> { [ 0x72, 0x52 ] };
#| key <AD09> { [ 0x6f, 0x4f ] };
#| key <RTRN> { [ 0xff0d ] };
#| key <AC03> { [ 0x64, 0x44 ] };
#| key <AB07> { [ 0x6d, 0x4d ] };
#| key <SPCE> { [ 0x20 ] };
#|};
#|};
let r = rig("hex-osk-remote", None, "")
let comp = r.comp
comp.server.set_keymap(@utf8.encode(hex_keymap))
comp.set_osk_enabled(true)
assert_false(comp.osk_is_visible())
let (_, ok) = comp.control_command("auth-demo")
assert_true(ok)
assert_true(r.settle(fn() { comp.auth_view().map(v => v.phase == Asking).unwrap_or(false) }))
assert_true(comp.osk_is_visible())
let d = r.view()
// Physical/hardware keyboard typing through hex-keysym keymap.
auth_type(comp, "de")
assert_eq(d.typed(), 2)
// Touch OSK tap reaches the password field.
let (mx, my) = comp.osk_key_center("m").unwrap()
click_at(comp, mx, my, 20U)
assert_eq(d.typed(), 3)
// Chandra Remote text commit routes to the password dialog.
assert_true(comp.remote_commit_text("o"))
assert_eq(d.typed(), 4)
auth_alt(comp, 19U)
assert_true(d.reveal)
assert_eq(d.field_text(), "demo")
// Manual OSK Hide dismisses it; tapping the password field brings it back.
let (hx, hy) = comp.osk_key_center("Hide").unwrap()
click_at(comp, hx, hy, 25U)
assert_false(comp.osk_is_visible())
auth_click(comp, Field)
assert_true(comp.osk_is_visible())
// Submitting authorizes and hides the OSK automatically.
auth_press(comp, 28U)
assert_true(r.settle(fn() { comp.auth_view() is None && comp.auth_demos.length() == 0 }))
assert_false(comp.osk_is_visible())
comp.close()
}