295 lines
11 KiB
Go
295 lines
11 KiB
Go
package guesttools
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os/exec"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/host"
|
|
)
|
|
|
|
func testTimezoneScripts(t *testing.T, sh, rootInstall string) {
|
|
t.Helper()
|
|
rewrite := strings.NewReplacer(
|
|
"/private/etc/sudoers.d", "system/sudoers.d",
|
|
"/private/etc", "system/etc",
|
|
"/private", "system",
|
|
"/Volumes/REIMSTOOLS", "tools",
|
|
"/var/db/timezone/zoneinfo", "zones",
|
|
"/usr/share/zoneinfo", "missing-zones",
|
|
"/usr/bin/stat", "mock_stat",
|
|
"/bin/ls", "mock_ls",
|
|
"/usr/bin/install", "mock_install",
|
|
"/usr/sbin/chown", "mock_chown",
|
|
"/usr/sbin/visudo", "mock_visudo",
|
|
"/usr/bin/curl", "mock_curl",
|
|
"/usr/bin/sudo", "mock_sudo",
|
|
"/bin/rm ", "mock_rm ",
|
|
"/bin/mv", "mock_mv",
|
|
)
|
|
run := func(t *testing.T, script string, args ...string) (string, error) {
|
|
t.Helper()
|
|
cmd := exec.Command(sh, append([]string{"-s", "--"}, args...)...)
|
|
cmd.Dir = t.TempDir()
|
|
cmd.Env = append(cmd.Environ(), "MSYS=winsymlinks:sys")
|
|
cmd.Stdin = strings.NewReader(timezoneShellFixture + rewrite.Replace(script))
|
|
out, err := cmd.CombinedOutput()
|
|
return string(out), err
|
|
}
|
|
t.Run("resolve_without_realpath", func(t *testing.T) {
|
|
validation := strings.ReplaceAll(guestTimezoneFile, "/usr/bin/realpath", "./unavailable-realpath")
|
|
script := validation + `
|
|
ln -s Shanghai zones/Asia/Link
|
|
ln -s "$(pwd -P)/zones/Asia/Link" zones/Alias
|
|
printf TZif > outside
|
|
ln -s ../outside zones/Escape
|
|
ln -s .. zones/DirectoryEscape
|
|
ln -s Missing zones/Dangling
|
|
ln -s LoopB zones/LoopA
|
|
ln -s LoopA zones/LoopB
|
|
[ "$(timezone_file Asia/Shanghai)" = zones/Asia/Shanghai ]
|
|
[ "$(timezone_file Alias)" = zones/Alias ]
|
|
for name in Escape DirectoryEscape/outside Dangling LoopA; do
|
|
if timezone_file "$name"; then exit 1; fi
|
|
done
|
|
if resolve_timezone_path zones/LoopA; then exit 1; fi
|
|
`
|
|
if out, err := run(t, script); err != nil {
|
|
t.Fatalf("timezone path fallback: %v\n%s", err, out)
|
|
}
|
|
})
|
|
t.Run("reports_failed_sync_and_clears_it", func(t *testing.T) {
|
|
report := scriptSection(t, string(GuestAgentScript()), "report_status() {", "\nread_local_clipboard() {")
|
|
script := guestTimezoneAgent + guestTimezoneConfig + report + `
|
|
. tools/config
|
|
TIMEZONE_HELPER=tools/set-timezone.sh
|
|
printf '#!/bin/sh\nexit 0\n' > "$TIMEZONE_HELPER"
|
|
chmod +x "$TIMEZONE_HELPER"
|
|
mount_mode=sync
|
|
sleep_active=false
|
|
current_timezone() { printf Asia/Shanghai; }
|
|
curl() {
|
|
while [ "$1" != "-d" ]; do shift; done
|
|
payload=$2
|
|
}
|
|
expect_timezone_error() {
|
|
case "$payload" in
|
|
*"\"timezone_error\":\"$1\""*) ;;
|
|
*) printf 'expected timezone_error=%s in %s\n' "$1" "$payload" >&2; return 1 ;;
|
|
esac
|
|
}
|
|
fail_sudo=1
|
|
sync_timezone '{"timezone":"Asia/Tokyo"}'
|
|
report_status
|
|
expect_timezone_error apply_failed
|
|
case "$payload" in
|
|
*'"timezone_helper_ready":true'*) ;;
|
|
*) printf 'expected a ready helper in %s\n' "$payload" >&2; exit 1 ;;
|
|
esac
|
|
sync_timezone '{"timezone":""}'
|
|
report_status
|
|
expect_timezone_error ""
|
|
sync_timezone '{"timezone":"Asia/Tokyo"}'
|
|
fail_sudo=0
|
|
sync_timezone '{"timezone":"Asia/Tokyo"}'
|
|
report_status
|
|
expect_timezone_error ""
|
|
`
|
|
if out, err := run(t, script); err != nil {
|
|
t.Fatalf("timezone agent status: %v\n%s", err, out)
|
|
}
|
|
})
|
|
for _, tc := range []struct{ name, setup, checks string }{
|
|
{"first_install", "", "[ \"$result\" -eq 0 ] && [ \"$(cat \"$helper\")\" = new-helper ] && grep -q '^#501 ALL=' \"$rule\""},
|
|
{"reinstall", "seed_old", "[ \"$result\" -eq 0 ] && [ \"$(cat \"$helper\")\" = new-helper ] && grep -q '^#501 ALL=' \"$rule\""},
|
|
{"rollback_reinstall", "seed_old; fail_visudo=1", "[ \"$result\" -ne 0 ] && [ \"$(cat \"$helper\")\" = old-helper ] && [ \"$(cat \"$rule\")\" = old-rule ]"},
|
|
{"rollback_failed_rule_replace", "seed_old; fail_rule_replace=1", "[ \"$result\" -ne 0 ] && [ \"$(cat \"$helper\")\" = old-helper ] && [ \"$(cat \"$rule\")\" = old-rule ]"},
|
|
{"rollback_first_install", "fail_visudo=1", "[ \"$result\" -ne 0 ] && [ ! -e \"$helper\" ] && [ ! -e \"$rule\" ]"},
|
|
{"reject_group_writable_parent", "parent_mode=0775", "[ \"$result\" -ne 0 ] && [ ! -e \"$helper\" ] && [ ! -e \"$rule\" ]"},
|
|
{"reject_group_writable_helper", "seed_old; helper_mode=0775", "[ \"$result\" -ne 0 ] && [ \"$(cat \"$helper\")\" = old-helper ] && [ \"$(cat \"$rule\")\" = old-rule ]"},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
script := tc.setup + "\nset +e\n(\n" + rootInstall + "\n)\nresult=$?\nset -e\n" +
|
|
"[ ! -e \"$helper.bak\" ] && [ ! -e \"$rule.bak\" ] && [ ! -e system/sudoers.d/.reims-timezone.lock ] || exit 1\n" + tc.checks + "\n"
|
|
if out, err := run(t, script, "501"); err != nil {
|
|
t.Fatalf("timezone install fixture: %v\n%s", err, out)
|
|
}
|
|
})
|
|
}
|
|
for _, tc := range []struct {
|
|
name, setup, message string
|
|
args []string
|
|
fail bool
|
|
}{
|
|
{"offline", "", "Could not read the current timezone policy", nil, true},
|
|
{"off", "bridge='{\"timezone\":\"\"}'", "no timezone to apply", nil, false},
|
|
{"online", "bridge='{\"timezone\":\"Asia/Shanghai\"}'", "applied Asia/Shanghai", nil, false},
|
|
{"offline_explicit", "", "applied Asia/Shanghai", []string{"Asia/Shanghai"}, false},
|
|
{"reject_non_TZif", "printf 'not zoneinfo' > zones/Asia/Shanghai", "Invalid IANA timezone", []string{"Asia/Shanghai"}, true},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
script := tc.setup + "\n" + guestApplyTimezone
|
|
out, err := run(t, script, tc.args...)
|
|
if (err != nil) != tc.fail || !strings.Contains(out, tc.message) ||
|
|
(tc.args == nil && tc.name != "online" && strings.Contains(out, "applied ")) {
|
|
t.Fatalf("apply timezone: %v\n%s", err, out)
|
|
}
|
|
})
|
|
}
|
|
t.Run("install_prompt_online_only", func(t *testing.T) {
|
|
prompt := scriptSection(t, string(GuestInstallScript()), "if [ -t 0 ]; then", "\nfi\n") + "\nfi\n"
|
|
prompt = strings.NewReplacer("[ -t 0 ]", "true", "read -r answer", "answer=n").Replace(prompt)
|
|
for _, tc := range []struct{ response, want string }{
|
|
{"", ""},
|
|
{`{"timezone":""}`, ""},
|
|
{`{"timezone":"Asia/Shanghai"}`, "Apply timezone Asia/Shanghai"},
|
|
} {
|
|
script := ". tools/config\nbridge='" + tc.response + "'\n" + guestTimezoneSelection + prompt
|
|
out, err := run(t, script)
|
|
if err != nil || (tc.want == "" && out != "") || !strings.HasPrefix(out, tc.want) {
|
|
t.Errorf("prompt for %q: %v\n%s", tc.response, err, out)
|
|
}
|
|
}
|
|
})
|
|
t.Run("uninstall_by_uid", func(t *testing.T) {
|
|
script := "seed_old\nuid=501\nprintf 'other\\n' > system/sudoers.d/reims-timezone-502\n" + guestTimezoneUninstall +
|
|
"\n[ ! -e \"$rule\" ] && [ \"$(cat \"$helper\")\" = old-helper ] && [ \"$(cat system/sudoers.d/reims-timezone-502)\" = other ] || exit 1\n" +
|
|
"uid=502\n" + guestTimezoneUninstall + "\n[ ! -e \"$helper\" ] && [ ! -e system/sudoers.d/reims-timezone-502 ]\n"
|
|
if out, err := run(t, script); err != nil {
|
|
t.Fatalf("timezone uninstall fixture: %v\n%s", err, out)
|
|
}
|
|
})
|
|
t.Run("uninstall_failure", func(t *testing.T) {
|
|
script := "seed_old\nuid=501\nfail_rm=$helper\n" + guestTimezoneUninstall + "\necho 'Uninstalled'\n"
|
|
out, err := run(t, script)
|
|
if err == nil || !strings.Contains(out, "Remaining Reims timezone file: system/etc/reims-timezone/set-timezone.sh") ||
|
|
!strings.Contains(out, "retry") || strings.Contains(out, "Uninstalled") {
|
|
t.Fatalf("timezone uninstall failure: %v\n%s", err, out)
|
|
}
|
|
})
|
|
}
|
|
|
|
const timezoneShellFixture = `
|
|
set -eu
|
|
parent_mode=0755
|
|
helper_mode=0755
|
|
helper=system/etc/reims-timezone/set-timezone.sh
|
|
rule=system/sudoers.d/reims-timezone-501
|
|
mkdir -p "${helper%/*}" system/sudoers.d tools zones/Asia
|
|
printf new-helper > tools/set-timezone.sh
|
|
printf TZif > zones/Asia/Shanghai
|
|
printf 'REIMS_TOKEN=test\nREIMS_HOST_URL=http://stub\n' > tools/config
|
|
seed_old() {
|
|
printf old-helper > "$helper"
|
|
printf old-rule > "$rule"
|
|
}
|
|
mock_stat() {
|
|
if [ "$2" = '%u' ]; then
|
|
echo 0
|
|
else
|
|
case "$3" in
|
|
system|system/etc) echo "$parent_mode" ;;
|
|
"$helper") echo "$helper_mode" ;;
|
|
*) echo 0755 ;;
|
|
esac
|
|
fi
|
|
}
|
|
mock_ls() { :; }
|
|
mock_install() { cp "$7" "$8"; }
|
|
mock_chown() { :; }
|
|
mock_visudo() { [ "$2" != "$rule" ] || [ "${fail_visudo:-0}" = 0 ]; }
|
|
mock_curl() { [ -n "${bridge:-}" ] && printf '%s\n' "$bridge"; }
|
|
mock_sudo() {
|
|
case "$1" in
|
|
-n)
|
|
[ "$2" != -l ] || return 0
|
|
[ "${fail_sudo:-0}" = 0 ] || return 1
|
|
printf 'applied %s\n' "$4"
|
|
;;
|
|
*)
|
|
if [ "$#" -eq 4 ] && [ "$4" = "${uid:-}" ]; then
|
|
shift 3
|
|
(eval "$(cat)")
|
|
else
|
|
cat >/dev/null
|
|
fi
|
|
;;
|
|
esac
|
|
}
|
|
mock_rm() {
|
|
[ "$2" != "${fail_rm:-}" ] || return 1
|
|
command rm "$@"
|
|
}
|
|
mock_mv() {
|
|
if [ "${fail_rule_replace:-0}" = 1 ] && [ "$3" = "$rule" ] && [ "$2" != "$rule.bak" ]; then
|
|
return 1
|
|
fi
|
|
command mv "$@"
|
|
}
|
|
`
|
|
|
|
func TestResolveEffectiveTimezone(t *testing.T) {
|
|
for _, tc := range []struct{ setting, host, want string }{
|
|
{"", "Asia/Shanghai", "Asia/Shanghai"},
|
|
{"host", "UTC", "UTC"},
|
|
{"host", "/UTC", ""},
|
|
{"host", "", ""},
|
|
{"off", "UTC", ""},
|
|
{"Asia/Tokyo", "UTC", "Asia/Tokyo"},
|
|
{"Asia/../UTC", "UTC", ""},
|
|
} {
|
|
if got := ResolveEffectiveTimezone(tc.setting, tc.host); got != tc.want {
|
|
t.Errorf("ResolveEffectiveTimezone(%q, %q) = %q, want %q", tc.setting, tc.host, got, tc.want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestTimezoneBridge(t *testing.T) {
|
|
const token = "timezone-bridge-token"
|
|
const vm = "mac"
|
|
srv := NewTransportServer(nil)
|
|
srv.RegisterVM(VMConfig{VMName: vm, Token: token})
|
|
for _, tc := range []struct{ setting, want string }{
|
|
{"", host.DetectHostTimezone()}, {"America/Argentina/Buenos_Aires", "America/Argentina/Buenos_Aires"}, {"off", ""},
|
|
} {
|
|
srv.SetTimezone(vm, token, tc.setting)
|
|
req := httptest.NewRequest(http.MethodGet, "/v1/config", nil)
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
res := httptest.NewRecorder()
|
|
srv.handleConfig(res, req)
|
|
var cfg map[string]json.RawMessage
|
|
if res.Code != http.StatusOK || json.Unmarshal(res.Body.Bytes(), &cfg) != nil {
|
|
t.Fatalf("config = %d %s", res.Code, res.Body)
|
|
}
|
|
var tz string
|
|
if err := json.Unmarshal(cfg["timezone"], &tz); err != nil || tz != tc.want {
|
|
t.Errorf("config timezone = %q, want %q (error %v)", tz, tc.want, err)
|
|
}
|
|
}
|
|
|
|
for _, tc := range []struct {
|
|
body, applied, timezoneError string
|
|
ready bool
|
|
version int
|
|
}{
|
|
{`{"agent_version":11,"timezone_applied":"Etc/GMT+8","timezone_helper_ready":true,"timezone_error":"apply_failed"}`, "Etc/GMT+8", "apply_failed", true, 11},
|
|
{`{"agent_version":11,"timezone_applied":"Asia/Tokyo","timezone_helper_ready":true,"timezone_error":""}`, "Asia/Tokyo", "", true, 11},
|
|
{`{"agent_version":11,"timezone_applied":"../UTC","timezone_helper_ready":true}`, "", "", true, 11},
|
|
{`{"agent_version":10}`, "", "", false, 10},
|
|
} {
|
|
req := httptest.NewRequest(http.MethodPost, "/v1/status", strings.NewReader(tc.body))
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
res := httptest.NewRecorder()
|
|
srv.handleStatus(res, req)
|
|
guest := srv.Status(vm, time.Minute)
|
|
if res.Code != http.StatusOK || !guest.Connected || guest.AgentVersion != tc.version ||
|
|
guest.TimezoneApplied != tc.applied || guest.TimezoneHelperReady != tc.ready || guest.TimezoneError != tc.timezoneError {
|
|
t.Errorf("status for %s = %d %+v", tc.body, res.Code, guest)
|
|
}
|
|
}
|
|
}
|