xref: /freebsd/libexec/nuageinit/tests/addsudo.lua (revision a49b3b10aae2db1f4a4ecf310fdedc80eb6bb7e2)
1#!/usr/libexec/flua
2---
3-- SPDX-License-Identifier: BSD-2-Clause
4--
5-- Copyright (c) 2026 Baptiste Daroussin <bapt@FreeBSD.org>
6
7local n = require("nuage")
8
9local root = os.getenv("NUAGE_FAKE_ROOTDIR")
10if not root then
11	root = ""
12end
13
14local function get_localbase()
15	local f = io.popen("sysctl -in user.localbase 2> /dev/null")
16	local lb = f:read("*l")
17	f:close()
18	if lb == nil or lb:len() == 0 then
19		lb = "/usr/local"
20	end
21	return lb
22end
23
24local function read_sudoers()
25	local path = root .. get_localbase() .. "/etc/sudoers.d/90-nuageinit-users"
26	local f = io.open(path, "r")
27	if not f then
28		return nil
29	end
30	local content = f:read("*a")
31	f:close()
32	return content
33end
34
35-- test with a single string rule
36n.addsudo({ name = "testuser", sudo = "ALL=(ALL) NOPASSWD:ALL" })
37local content = read_sudoers()
38if not content then
39	n.err("sudoers file not created")
40end
41if content ~= "testuser ALL=(ALL) NOPASSWD:ALL\n" then
42	n.err("unexpected sudoers content for string rule: '" .. content .. "'")
43end
44
45-- remove file for next test
46os.remove(root .. get_localbase() .. "/etc/sudoers.d/90-nuageinit-users")
47
48-- test with a table of rules
49n.addsudo({
50	name = "testuser",
51	sudo = { "ALL=(ALL) NOPASSWD:/usr/sbin/pw", "ALL=(ALL) ALL" }
52})
53content = read_sudoers()
54if not content then
55	n.err("sudoers file not created for table")
56end
57if content ~= "testuser ALL=(ALL) NOPASSWD:/usr/sbin/pw\ntestuser ALL=(ALL) ALL\n" then
58	n.err("unexpected sudoers content for table: '" .. content .. "'")
59end
60
61os.exit(0)
62