From ae5e9797612a700df13f1676ce4125d1a9059386 Mon Sep 17 00:00:00 2001 From: cabbage Date: Tue, 27 Oct 2026 08:54:23 +0000 Subject: [PATCH] feat(windows): simplify tray controls and allow installer-user config edits --- cmd/rvbox/installer_other.go | 2 +- cmd/rvbox/installer_windows.go | 47 ++++- cmd/rvbox/installer_windows_test.go | 54 ++++++ cmd/rvbox/main.go | 20 +- cmd/rvbox/service_windows.go | 8 +- cmd/rvbox/tray_status_windows_test.go | 26 +++ docs/implementation-plan.v1.md | 42 +++-- docs/platform-and-operations.md | 24 ++- docs/testing.md | 20 ++ internal/client/windowsservice/service.go | 8 + .../client/windowsservice/service_other.go | 1 + .../client/windowsservice/service_windows.go | 46 +++++ .../client/windowstray/native_windows_test.go | 47 ++++- internal/client/windowstray/service_other.go | 2 +- internal/client/windowstray/status.go | 68 +++++++ internal/client/windowstray/status_test.go | 65 +++++++ internal/client/windowstray/tray_windows.go | 177 ++++++++++++------ test/coverage.toml | 42 +++++ 18 files changed, 611 insertions(+), 88 deletions(-) create mode 100644 cmd/rvbox/tray_status_windows_test.go create mode 100644 internal/client/windowstray/status.go create mode 100644 internal/client/windowstray/status_test.go diff --git a/cmd/rvbox/installer_other.go b/cmd/rvbox/installer_other.go index a45e144..f57daaf 100644 --- a/cmd/rvbox/installer_other.go +++ b/cmd/rvbox/installer_other.go @@ -11,6 +11,6 @@ func runInteractiveInstaller(io.Writer, io.Writer) error { return errors.New("the v1 interactive installer is implemented for Windows only") } -func installPackagedDefault(io.Writer) error { +func installPackagedDefault(string, io.Writer) error { return errors.New("the v1 packaged installer is implemented for Windows only") } diff --git a/cmd/rvbox/installer_windows.go b/cmd/rvbox/installer_windows.go index b6181b2..e686f34 100644 --- a/cmd/rvbox/installer_windows.go +++ b/cmd/rvbox/installer_windows.go @@ -73,6 +73,10 @@ type shellExecuteInfo struct { } func runElevatedInstaller(executable string) error { + userSID, err := installerConfigUserSID("") + if err != nil { + return fmt.Errorf("identify installing user: %w", err) + } runtime.LockOSThread() defer runtime.UnlockOSThread() // Shell extensions may require COM. Balance both S_OK and S_FALSE, while @@ -91,7 +95,7 @@ func runElevatedInstaller(executable string) error { Size: uint32(unsafe.Sizeof(shellExecuteInfo{})), Mask: 0x40 | 0x100, // SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC. Verb: installerUTF16("runas"), File: file, - Parameters: installerUTF16("--install-default"), Show: windows.SW_SHOWNORMAL, + Parameters: installerUTF16("--install-default --config-user-sid " + userSID.String()), Show: windows.SW_SHOWNORMAL, } result, _, callErr := installerShellExecute.Call(uintptr(unsafe.Pointer(&info))) if result == 0 { @@ -141,8 +145,8 @@ func startInstalledTray() error { // installPackagedDefault executes only in the UAC-elevated child. It preserves // a pre-existing operator configuration, atomically updates the executable, // installs/updates the SCM service, and starts it. -func installPackagedDefault(_ io.Writer) error { - err := installPackagedDefaultFiles() +func installPackagedDefault(userSID string, _ io.Writer) error { + err := installPackagedDefaultFiles(userSID) if err != nil { showInstallerMessage("RVBox could not be installed.\n\n"+err.Error()+"\n\nNo existing configuration was replaced.", installerErrorIcon) return err @@ -152,10 +156,14 @@ func installPackagedDefault(_ io.Writer) error { return nil } -func installPackagedDefaultFiles() error { +func installPackagedDefaultFiles(userSID string) error { if strings.TrimSpace(bootstrapServerURL) == "" { return errors.New("this RVBox package was built without a bootstrap server URL") } + configUser, err := installerConfigUserSID(userSID) + if err != nil { + return fmt.Errorf("validate config user: %w", err) + } source, err := os.Executable() if err != nil { return fmt.Errorf("locate installer executable: %w", err) @@ -199,6 +207,11 @@ func installPackagedDefaultFiles() error { } else if err != nil { return fmt.Errorf("inspect existing configuration: %w", err) } + // Apply this on upgrades too, without rewriting operator configuration. + // Only the TOML gets user read/write; the spool retains its private ACL. + if err := protectMachineConfig(configPath, configUser); err != nil { + return err + } if err := windowsservice.Install(windowsservice.InstallSpec{ExecutablePath: targetExecutable, ConfigPath: configPath, Startup: windowsservice.StartupAutomatic}); err != nil { return fmt.Errorf("install and start RVBox service: %w", err) } @@ -257,11 +270,31 @@ func writeMachineConfig(path string, content []byte) error { _ = os.Remove(temporary) return fmt.Errorf("activate default configuration: %w", err) } - return protectMachineConfig(path) + return nil } -func protectMachineConfig(path string) error { - descriptor, err := windows.SecurityDescriptorFromString("D:P(A;;FA;;;SY)(A;;FA;;;BA)") +func installerConfigUserSID(requested string) (*windows.SID, error) { + if requested != "" { + return windows.StringToSid(requested) + } + var token windows.Token + if err := windows.OpenProcessToken(windows.CurrentProcess(), windows.TOKEN_QUERY, &token); err != nil { + return nil, err + } + defer token.Close() + user, err := token.GetTokenUser() + if err != nil { + return nil, err + } + // Copy away from the token-information buffer before returning. + return windows.StringToSid(user.User.Sid.String()) +} + +func protectMachineConfig(path string, user *windows.SID) error { + if user == nil { + return errors.New("config user SID is required") + } + descriptor, err := windows.SecurityDescriptorFromString(fmt.Sprintf("D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;GRGW;;;%s)", user.String())) if err != nil { return err } diff --git a/cmd/rvbox/installer_windows_test.go b/cmd/rvbox/installer_windows_test.go index 36b1cd1..278dc59 100644 --- a/cmd/rvbox/installer_windows_test.go +++ b/cmd/rvbox/installer_windows_test.go @@ -3,7 +3,11 @@ package main import ( + "golang.org/x/sys/windows" + "os" + "path/filepath" "runtime" + "strings" "testing" "unsafe" ) @@ -17,3 +21,53 @@ func TestInstallerShellExecuteInfoLayout_HP_WINCLI_07(t *testing.T) { t.Fatalf("SHELLEXECUTEINFOW layout mismatch: size=%d instance=%d process=%d", unsafe.Sizeof(info), unsafe.Offsetof(info.Instance), unsafe.Offsetof(info.Process)) } } + +func TestInstallerConfigACLAllowsOriginalUser_HP_WINCLI_08(t *testing.T) { + user, err := installerConfigUserSID("") + if err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "client.toml") + want := []byte("[client]\nclient_id = \"preserved\"\n") + if err := os.WriteFile(path, want, 0600); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + if err := protectMachineConfig(path, user); err != nil { + t.Fatal(err) + } + } + file, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatalf("original user cannot edit config: %v", err) + } + _ = file.Close() + got, err := os.ReadFile(path) + if err != nil || string(got) != string(want) { + t.Fatalf("configuration rewritten: %q, %v", got, err) + } + sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION) + if err != nil { + t.Fatal(err) + } + acl := sd.String() + if !strings.Contains(acl, user.String()) || strings.Contains(acl, ";;;WD)") || strings.Contains(acl, ";;;BU)") || !strings.Contains(acl, "D:P") { + t.Fatalf("config ACL widened beyond selected user: %s", acl) + } + if err := protectMachineConfig(path, nil); err == nil { + t.Fatal("nil installer SID accepted") + } +} + +func TestInstallerConfigUserSIDValidation_BH_WINCLI_02(t *testing.T) { + for _, value := range []string{"not-a-sid", "S-1-5-21-1)(A;;FA;;;WD)", "S-1-5-21-1\x00"} { + if _, err := installerConfigUserSID(value); err == nil { + t.Fatalf("invalid SID accepted: %q", value) + } + } + const other = "S-1-5-21-111-222-333-444" + user, err := installerConfigUserSID(other) + if err != nil || user.String() != other { + t.Fatalf("original user SID lost across elevation: %v, %v", user, err) + } +} diff --git a/cmd/rvbox/main.go b/cmd/rvbox/main.go index 114b0ec..75089e1 100644 --- a/cmd/rvbox/main.go +++ b/cmd/rvbox/main.go @@ -12,6 +12,7 @@ import ( "net/http" "os" "runtime" + "sync/atomic" "time" rvboxv1 "github.com/rvbox/rvbox/gen/go/rvbox/v1" @@ -38,6 +39,10 @@ func main() { var nativeTestContextFailures map[clientwindows.ExecutionContext]bool +// A single daemon process owns this reconciled-session fact. The local tray +// reads it without requiring the optional observability HTTP listener. +var clientSessionReady atomic.Bool + // bootstrapServerURL is set only for a packaged Windows installer. A fresh // machine has no service connection from which it could discover this value, // so release packaging must deliberately supply the intended WSS endpoint. @@ -69,6 +74,7 @@ func run(args []string, output, diagnostics io.Writer) error { checkConfig := flags.Bool("check-config", false, "validate client configuration and exit") install := flags.Bool("install-service", false, "install or update the machine-wide service") installDefault := flags.Bool("install-default", false, "install the packaged default configuration (internal installer use)") + configUserSID := flags.String("config-user-sid", "", "original interactive installer user SID (internal installer use)") uninstall := flags.Bool("uninstall-service", false, "remove the machine-wide service") configure := flags.Bool("configure-service", false, "configure machine-wide service startup mode") startup := flags.String("startup", string(windowsservice.StartupAutomatic), "service startup mode: automatic or manual") @@ -91,6 +97,9 @@ func run(args []string, output, diagnostics io.Writer) error { if selected != 1 { return errors.New("select exactly one rvbox mode") } + if *configUserSID != "" && !*installDefault { + return errors.New("--config-user-sid is only valid with --install-default") + } if *checkConfig { configured, err := loadClientConfig(*configPath) if err != nil { @@ -107,7 +116,7 @@ func run(args []string, output, diagnostics io.Writer) error { return windowsservice.Install(windowsservice.InstallSpec{ExecutablePath: executable, ConfigPath: *configPath, Startup: windowsservice.StartupAutomatic}) } if *installDefault { - return installPackagedDefault(diagnostics) + return installPackagedDefault(*configUserSID, diagnostics) } if *uninstall { return windowsservice.Uninstall() @@ -162,6 +171,8 @@ func loadClientConfig(path string) (*config.Client, error) { } func runClientDaemon(ctx context.Context, configPath string, diagnostics io.Writer) error { + clientSessionReady.Store(false) + defer clientSessionReady.Store(false) configured, err := loadClientConfig(configPath) if err != nil { return err @@ -245,8 +256,11 @@ func runClientDaemon(ctx context.Context, configPath string, diagnostics io.Writ Jitter: agent.CryptoJitter, Now: func() time.Time { return time.Now().UTC() }, OnDispatch: executor.Dispatch, OnScriptReady: executor.ScriptReady, OnStdin: executor.Stdin, OnCloseStdin: executor.CloseStdin, OnSignal: executor.Signal, OnTerminate: executor.Terminate, EventReady: eventReady, - Metrics: health, - OnSessionActive: health.SetReady, + Metrics: health, + OnSessionActive: func(ready bool) { + clientSessionReady.Store(ready) + health.SetReady(ready) + }, OnSessionError: func(sessionErr error) { if diagnostics != nil { _, _ = fmt.Fprintf(diagnostics, "rvbox client session retry: %v\n", sessionErr) diff --git a/cmd/rvbox/service_windows.go b/cmd/rvbox/service_windows.go index 218a58b..5c71269 100644 --- a/cmd/rvbox/service_windows.go +++ b/cmd/rvbox/service_windows.go @@ -123,8 +123,7 @@ func applyServiceDiagnosticsACL(path string) error { } func runTray(configPath string, diagnostics io.Writer) error { - _ = configPath // the tray obtains the canonical paths from the service. - return windowstray.Run(context.Background(), diagnostics) + return windowstray.Run(context.Background(), configPath, diagnostics) } func runLauncher(channel string, _ io.Writer) error { @@ -139,7 +138,10 @@ func handleTrayRequest(ctx context.Context, configPath string, request windowstr response := windowstray.Frame{Action: windowstray.ActionStatus} switch request.Action { case windowstray.ActionStatus: - response.Payload = []byte("RVBox service=running") + response.Payload = []byte("disconnected") + if clientSessionReady.Load() { + response.Payload = []byte("running") + } case windowstray.ActionOpenConfig: response.Payload = []byte(configPath) case windowstray.ActionOpenLog: diff --git a/cmd/rvbox/tray_status_windows_test.go b/cmd/rvbox/tray_status_windows_test.go new file mode 100644 index 0000000..768be4d --- /dev/null +++ b/cmd/rvbox/tray_status_windows_test.go @@ -0,0 +1,26 @@ +//go:build windows + +package main + +import ( + "context" + "testing" + + "github.com/rvbox/rvbox/internal/client/windowstray" +) + +func TestTrayConnectionStatusWithoutObservability_HP_WINCLI_09(t *testing.T) { + previous := clientSessionReady.Load() + defer clientSessionReady.Store(previous) + for _, ready := range []bool{false, true, false} { + clientSessionReady.Store(ready) + response, err := handleTrayRequest(context.Background(), `C:\ProgramData\RVBox\client.toml`, windowstray.Frame{Action: windowstray.ActionStatus}) + want := "disconnected" + if ready { + want = "running" + } + if err != nil || string(response.Payload) != want { + t.Fatalf("ready=%t response=%q err=%v", ready, response.Payload, err) + } + } +} diff --git a/docs/implementation-plan.v1.md b/docs/implementation-plan.v1.md index 94cc293..c0be358 100644 --- a/docs/implementation-plan.v1.md +++ b/docs/implementation-plan.v1.md @@ -35,8 +35,8 @@ nor commands. Task Scheduler is not used anywhere in v1. Use conventional machine-wide paths: `%ProgramData%\RVBox\client.toml`, `%ProgramData%\RVBox\state`, and `%ProgramData%\RVBox\logs\rvbox.log`, with -state ACLs limited to Administrators and SYSTEM and separate read-only tray -access for config/log. The menu opens the exact config or current log via a safe +state ACLs limited to Administrators and SYSTEM, read/write config access for +the original installing user, and separate current-log access. The menu opens the exact config or current log via a safe explicit file-opening path. SCM Automatic/Manual state is the only service-startup source of truth and is not mirrored into TOML. Create `%ProgramData%\RVBox\work` as a SYSTEM-owned root. For omitted CWDs, create an @@ -2300,7 +2300,17 @@ to start the tray must explicitly report the already-installed service rather than claiming complete success. No sign-out or reboot is required. Run its Win32 message pump on one locked OS thread, recreate the icon after `TaskbarCreated`, and use bounded nonblocking IPC/UI -channels. The tooltip shows connection/readiness/dirty state without payloads. +channels. Show a disabled `Status: ...` banner first in the context menu, with +no clickable Status action. `running` requires a reconciled WSS session, +`disconnected` means SCM running without confirmed connectivity, and `stopped` +comes from SCM independently of IPC. Query SCM with only CONNECT plus +QUERY_STATUS/QUERY_CONFIG permissions; poll asynchronously every two seconds +and on menu opening. Keep status work separate from user actions so a stalled +poll cannot swallow clicks. Update an open menu and tooltip on the UI thread. +Expose Start/Stop service only (no Restart item). Combine Automatic/Manual into +one checked `Auto start` item. Checked state always comes from SCM, not an +optimistic toggle; cancelled/failed UAC must leave it unchanged. Keep the CLI +restart mode for operational use. The tooltip shows bounded status without payloads. `Exit` closes only that tray. The service continues through tray exit, user logoff, Explorer restart, and periods with no interactive user. @@ -2317,25 +2327,31 @@ request read can deadlock both peers. Keep a response alive until client disconnect or the peer deadline. Create the icon independently of IPC and post bounded status/action responses back to the UI thread. The tray never reads the spool/database. Read-only status may be served to a -local interactive user. For a mutating service/config action, the tray launches -the narrow canonical `configure-service` mode with UAC; that helper sends one -authenticated request and exits. The service rechecks the helper token rather -than trusting a tray-supplied administrator claim. +local interactive user. For a mutating service/startup action, the tray launches +the narrow canonical service-control mode with UAC; that helper calls SCM with +its elevated token and exits. SCM enforces authorization rather than trusting +a tray-supplied administrator claim. -Resolve defaults under `%ProgramData%\RVBox`; create the config, state, and log +Resolve defaults under `%ProgramData%\RVBox`; create private state and log directories with explicit Administrators/SYSTEM ACLs and reject insecure existing objects. Create `%ProgramData%\RVBox\work` as a SYSTEM-owned root and create identity-scoped child directories on demand with non-inherited ACLs for SYSTEM plus the effective non-SYSTEM SID; no command identity receives state- -directory access. Give tray users only the documented read access to config/ -current logs. On first installation, copy the annotated Windows +directory access. Grant the original installing user's SID read/write on the +TOML only, retaining SYSTEM/Administrators full access. Capture that SID in the +unelevated parent before UAC; validate/canonicalize it in the child before +SDDL construction, never use Everyone/Users as a default edit grant. Apply +the file ACL to existing configs during reinstall without changing contents; +do not widen spool ACLs. Give tray users only the documented access to current +logs. On first installation, copy the annotated Windows TOML template and leave the service live/not-ready until routing is valid. `Open config` and `Open log` use exact resolved regular paths—never an unquoted shell -command—and show actionable errors. Config edits are administrator-only and -take effect after explicit service restart; v1 has no hot reload or TOML rewrite. +command—and show actionable errors. Open config uses the explicit installed +path even when the service is stopped. Config edits by the installing user +take effect after explicit service stop/start; v1 has no hot reload or TOML rewrite. Install the service with `SERVICE_AUTO_START`. `configure-service` maps the tray -Automatic/Manual control directly to SCM start type; there is no +single `Auto start` checkbox directly to SCM start type; there is no `windows.start_on_boot` TOML key or second desired-state store. Stop/restart is a separate administrator action and reports that stopping the service terminates all supervised Jobs. Uninstall first stops admission, performs bounded orderly diff --git a/docs/platform-and-operations.md b/docs/platform-and-operations.md index e0ee362..adf95e8 100644 --- a/docs/platform-and-operations.md +++ b/docs/platform-and-operations.md @@ -109,11 +109,22 @@ deadlines/cancellation; neither peer uses an unbounded pipe flush. The icon is created before any IPC, with status/actions exchanged asynchronously so a stopped or stalled service cannot hide the icon or freeze its message loop. Read-only health/status is available to an interactive local user. Service -start/stop/restart, Automatic/Manual startup changes, config editing, incident +start/stop, startup changes, incident resolution, and other machine-wide mutations require a locally elevated administrator helper. `Exit` closes only that tray. Server Core and logged-out machines simply have no tray. +The menu starts with a disabled, informational `Status: ...` banner rather +than a clickable Status command. `running` means the service has a reconciled +server connection; `disconnected` means SCM reports running but no active +connection is confirmed; `stopped` comes from SCM even when the pipe is absent. +Pending/unknown SCM states are shown explicitly. Refresh status asynchronously +every two seconds and when opening the menu. Read-only SCM queries request +only CONNECT, QUERY_STATUS, and QUERY_CONFIG rights. The menu provides Start +service and Stop service, not Restart. A single checked `Auto start` item +reflects SCM Automatic/Manual configuration; clicking it requests the opposite +mode with UAC and waits for a subsequent SCM query before changing the tick. + When no config path was installed, resolve `FOLDERID_ProgramData` with the Windows Known Folder API and use `RVBox\client.toml`, `RVBox\state`, `RVBox\work`, and `RVBox\logs\rvbox.log` beneath it. Do not expand @@ -124,8 +135,15 @@ active-user context, a LocalService directory, or a SYSTEM-only directory for each SYSTEM context. Its non-inherited ACL grants only SYSTEM and the effective non-SYSTEM SID the required access. The service validates the existing owner, ACL, and reparse-point state before reuse, so one user cannot pre-create or -modify another identity's work area. Config/log read access needed by the tray -is separate from edit access. First installation writes the annotated template +modify another identity's work area. The default TOML grants read/write to the +original user who launched the installer, plus full access to SYSTEM and +Administrators. The unelevated installer captures that user's SID before UAC +and passes it to its elevated child, including over-the-shoulder elevation with +another account. Reinstallation repairs the TOML ACL without rewriting its +contents. This is a deliberate v1 configuration-control grant, not access to +private state or permission to start/stop the service without UAC. Open config +uses the installed explicit config path and also works while the service is +stopped. Current-log access is separate. First installation writes the annotated template and lets the service remain live but not ready until routing validates. Configuration is restart-only. File opening uses exact resolved regular paths, never a constructed shell command. diff --git a/docs/testing.md b/docs/testing.md index f8996ba..ee65146 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -200,6 +200,26 @@ test success. The UI case briefly creates/removes its own test icon. Session 0 runs verify rejection/transport but skip the actual desktop-window case, so they do not substitute for the interactive run. +For checks against the installed tray itself, run the probe/test runner from +Explorer's desktop (for example, the VM's Run dialog), not merely a process +with an active-user token. Matching WTS session IDs alone does not prove that +the probe shares Explorer's window station/desktop; a service-created command +can otherwise report a false-negative window lookup. Transfer the console test +executables separately from the installed service image and write bounded logs +to the run's owned test-artifact directory. + +The status/menu tests additionally cover connected versus disconnected versus +stopped, missing/stalled IPC, pending SCM states, a disabled status banner, +exactly one Auto start checkbox, no Restart menu item, native disabled/checked +flags, menu refresh after a state change, and normal-user read-only SCM access. +Installer tests verify the original pre-UAC user SID survives elevation, invalid +SID strings cannot enter SDDL, config ACL repair preserves contents and grants +that user read/write without an Everyone/Users grant, and status reporting does +not depend on the optional HTTP observability endpoint. Acceptance checks must +also prove config can be opened/saved unelevated, spool ACLs remain private, +Auto start reflects actual SCM state after successful or cancelled UAC, and a +live server disconnect/reconnect changes the banner without stopping the daemon. + `cmd/rvbox/installer_flow_test.go` checks install-before-tray ordering, cancelled/ failed elevation, and explicit partial success when tray startup fails. The native installer structure-layout test is in `installer_windows_test.go`. diff --git a/internal/client/windowsservice/service.go b/internal/client/windowsservice/service.go index 85967de..b60d22e 100644 --- a/internal/client/windowsservice/service.go +++ b/internal/client/windowsservice/service.go @@ -68,6 +68,13 @@ const ( StatePaused ) +// Status is read-only SCM state. Query never requests service mutation rights. +type Status struct { + Installed bool + State State + Startup StartupMode +} + type Command uint8 const ( @@ -118,6 +125,7 @@ func Transition(state State, command Command) (State, error) { // Install, Uninstall, Start, and Stop are intentionally narrow. Their // platform implementations return ErrUnsupported on non-Windows builds. func Install(spec InstallSpec) error { return installNative(spec) } +func Query() (Status, error) { return queryNative() } func Uninstall() error { return uninstallNative() } func Configure(startup StartupMode) error { return configureNative(startup) } func Start() error { return startNative() } diff --git a/internal/client/windowsservice/service_other.go b/internal/client/windowsservice/service_other.go index c675554..ea4fb2c 100644 --- a/internal/client/windowsservice/service_other.go +++ b/internal/client/windowsservice/service_other.go @@ -4,6 +4,7 @@ package windowsservice import "context" +func queryNative() (Status, error) { return Status{}, ErrUnsupported } func installNative(InstallSpec) error { return ErrUnsupported } func uninstallNative() error { return ErrUnsupported } func configureNative(StartupMode) error { return ErrUnsupported } diff --git a/internal/client/windowsservice/service_windows.go b/internal/client/windowsservice/service_windows.go index c33fdac..eeac0fc 100644 --- a/internal/client/windowsservice/service_windows.go +++ b/internal/client/windowsservice/service_windows.go @@ -19,6 +19,52 @@ func connect() (*mgr.Mgr, error) { return mgr.Connect() } +func queryNative() (Status, error) { + manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_CONNECT) + if err != nil { + return Status{}, err + } + defer windows.CloseServiceHandle(manager) + name, _ := windows.UTF16PtrFromString(Name) + handle, err := windows.OpenService(manager, name, windows.SERVICE_QUERY_STATUS|windows.SERVICE_QUERY_CONFIG) + if errors.Is(err, windows.ERROR_SERVICE_DOES_NOT_EXIST) { + return Status{State: StateStopped}, nil + } + if err != nil { + return Status{}, err + } + defer windows.CloseServiceHandle(handle) + service := mgr.Service{Name: Name, Handle: handle} + status, err := service.Query() + if err != nil { + return Status{}, err + } + configuration, err := service.Config() + if err != nil { + return Status{}, err + } + state := StateUnknown + switch status.State { + case svc.Running: + state = StateRunning + case svc.Stopped: + state = StateStopped + case svc.StartPending, svc.ContinuePending: + state = StateStartPending + case svc.StopPending: + state = StateStopPending + case svc.Paused, svc.PausePending: + state = StatePaused + } + startup := StartupMode("") + if configuration.StartType == mgr.StartAutomatic { + startup = StartupAutomatic + } else if configuration.StartType == mgr.StartManual { + startup = StartupManual + } + return Status{Installed: true, State: state, Startup: startup}, nil +} + func installNative(spec InstallSpec) error { if err := spec.Validate(); err != nil { return err diff --git a/internal/client/windowstray/native_windows_test.go b/internal/client/windowstray/native_windows_test.go index 7ec4b6f..186a2f6 100644 --- a/internal/client/windowstray/native_windows_test.go +++ b/internal/client/windowstray/native_windows_test.go @@ -13,9 +13,54 @@ import ( "time" "unsafe" + "github.com/rvbox/rvbox/internal/client/windowsservice" winapi "golang.org/x/sys/windows" ) +func TestNativeTrayReadOnlyServiceQuery_HP_WINTRAY_07(t *testing.T) { + status, err := windowsservice.Query() + if err != nil { + t.Fatalf("unprivileged read-only SCM query: %v", err) + } + if !status.Installed && status.State != windowsservice.StateStopped { + t.Fatalf("missing service state=%#v", status) + } + if status.Installed && status.State == windowsservice.StateUnknown { + t.Fatalf("installed service state=%#v", status) + } +} + +func TestNativeTrayMenuFlagsAndRefresh_HP_WINTRAY_08(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + menu, _, err := procCreatePopup.Call() + if menu == 0 { + t.Fatal(err) + } + defer procDestroyMenu.Call(menu) + w := &trayWindow{menu: menu, status: MenuStatus{Label: "Status: running", AutoStart: true, StartupKnown: true, CanStop: true}} + for _, item := range trayMenu(w.status) { + flags, text := menuItemFlags(item) + if ok, _, err := procAppendMenu.Call(menu, flags, uintptr(item.Action), uintptr(unsafe.Pointer(text))); ok == 0 { + t.Fatal(err) + } + } + getState := user32Tray.NewProc("GetMenuState") + banner, _, _ := getState.Call(menu, 0, trayMFByPosition) + auto, _, _ := getState.Call(menu, 7, trayMFByPosition) + if banner == ^uintptr(0) || banner&trayMFDisabled == 0 || auto&trayMFChecked == 0 { + t.Fatalf("initial menu flags banner=%#x auto=%#x", banner, auto) + } + w.status = MenuStatus{Label: "Status: stopped", StartupKnown: true, CanStart: true} + w.refreshMenu() + auto, _, _ = getState.Call(menu, 7, trayMFByPosition) + start, _, _ := getState.Call(menu, 5, trayMFByPosition) + stop, _, _ := getState.Call(menu, 6, trayMFByPosition) + if auto&trayMFChecked != 0 || start&trayMFDisabled != 0 || stop&trayMFDisabled == 0 { + t.Fatalf("updated menu flags start=%#x stop=%#x auto=%#x", start, stop, auto) + } +} + func trayTestName() string { return fmt.Sprintf(`\\.\pipe\rvbox-tray-test-%d-%d`, winapi.GetCurrentProcessId(), time.Now().UnixNano()) } @@ -206,7 +251,7 @@ func TestNativeTrayWindowLifecycle_HP_WINTRAY_04(t *testing.T) { defer cancel() ready := make(chan *trayWindow, 1) done := make(chan error, 1) - go runTrayMessageLoop(ctx, io.Discard, "RVBox native tray test", ready, done) + go runTrayMessageLoop(ctx, io.Discard, "RVBox native tray test", ready, done, "") var window *trayWindow select { case window = <-ready: diff --git a/internal/client/windowstray/service_other.go b/internal/client/windowstray/service_other.go index ed8a09a..8f07f89 100644 --- a/internal/client/windowstray/service_other.go +++ b/internal/client/windowstray/service_other.go @@ -17,7 +17,7 @@ func Serve(context.Context, Handler) error { return ErrUnsupported } func Request(context.Context, Frame) (Frame, error) { return Frame{}, ErrUnsupported } -func Run(context.Context, io.Writer) error { return ErrUnsupported } +func Run(context.Context, string, io.Writer) error { return ErrUnsupported } func WaitReady(context.Context) error { return ErrUnsupported } diff --git a/internal/client/windowstray/status.go b/internal/client/windowstray/status.go new file mode 100644 index 0000000..372932a --- /dev/null +++ b/internal/client/windowstray/status.go @@ -0,0 +1,68 @@ +package windowstray + +import "github.com/rvbox/rvbox/internal/client/windowsservice" + +// MenuStatus contains only presentation facts, never configuration or spool data. +type MenuStatus struct { + Label string + AutoStart bool + StartupKnown bool + CanStart bool + CanStop bool +} + +func menuStatus(service windowsservice.Status, queryErr error, connection string) MenuStatus { + result := MenuStatus{Label: "Status: unavailable"} + if queryErr != nil { + return result + } + result.StartupKnown = service.Installed && (service.Startup == windowsservice.StartupAutomatic || service.Startup == windowsservice.StartupManual) + result.AutoStart = service.Startup == windowsservice.StartupAutomatic + switch service.State { + case windowsservice.StateStopped: + result.Label = "Status: stopped" + result.CanStart = service.Installed + case windowsservice.StateStartPending: + result.Label = "Status: starting" + case windowsservice.StateStopPending: + result.Label = "Status: stopping" + case windowsservice.StatePaused: + result.Label, result.CanStop = "Status: paused", true + case windowsservice.StateRunning: + result.Label, result.CanStop = "Status: disconnected", true + if connection == "running" { + result.Label = "Status: running" + } + } + return result +} + +func automaticAction(automatic bool) Action { + if automatic { + return ActionSetManual + } + return ActionSetAutomatic +} + +type menuItem struct { + Action Action + Label string + Disabled bool + Checked bool + Separator bool +} + +func trayMenu(status MenuStatus) []menuItem { + return []menuItem{ + {Label: status.Label, Disabled: true}, + {Separator: true}, + {Action: ActionOpenConfig, Label: "Open config"}, + {Action: ActionOpenLog, Label: "Open log"}, + {Separator: true}, + {Action: ActionStartService, Label: "Start service", Disabled: !status.CanStart}, + {Action: ActionStopService, Label: "Stop service", Disabled: !status.CanStop}, + {Action: ActionSetAutomatic, Label: "Auto start", Disabled: !status.StartupKnown, Checked: status.AutoStart}, + {Separator: true}, + {Action: ActionExitTray, Label: "Exit"}, + } +} diff --git a/internal/client/windowstray/status_test.go b/internal/client/windowstray/status_test.go new file mode 100644 index 0000000..07f6448 --- /dev/null +++ b/internal/client/windowstray/status_test.go @@ -0,0 +1,65 @@ +package windowstray + +import ( + "errors" + "strings" + "testing" + + "github.com/rvbox/rvbox/internal/client/windowsservice" +) + +func TestTrayStatusUsesSCMAndConnection_HP_WINTRAY_05(t *testing.T) { + for _, tc := range []struct { + name string + service windowsservice.Status + err error + connection string + label string + start, stop, auto, known bool + }{ + {"connected", windowsservice.Status{Installed: true, State: windowsservice.StateRunning, Startup: windowsservice.StartupAutomatic}, nil, "running", "Status: running", false, true, true, true}, + {"disconnected", windowsservice.Status{Installed: true, State: windowsservice.StateRunning, Startup: windowsservice.StartupManual}, nil, "disconnected", "Status: disconnected", false, true, false, true}, + {"unresponsive pipe", windowsservice.Status{Installed: true, State: windowsservice.StateRunning, Startup: windowsservice.StartupAutomatic}, nil, "", "Status: disconnected", false, true, true, true}, + {"stopped ignores stale connection", windowsservice.Status{Installed: true, State: windowsservice.StateStopped, Startup: windowsservice.StartupAutomatic}, nil, "running", "Status: stopped", true, false, true, true}, + {"starting", windowsservice.Status{Installed: true, State: windowsservice.StateStartPending, Startup: windowsservice.StartupManual}, nil, "", "Status: starting", false, false, false, true}, + {"stopping", windowsservice.Status{Installed: true, State: windowsservice.StateStopPending, Startup: windowsservice.StartupAutomatic}, nil, "running", "Status: stopping", false, false, true, true}, + {"not installed", windowsservice.Status{State: windowsservice.StateStopped}, nil, "", "Status: stopped", false, false, false, false}, + {"access denied", windowsservice.Status{}, errors.New("access denied"), "running", "Status: unavailable", false, false, false, false}, + {"unknown startup", windowsservice.Status{Installed: true, State: windowsservice.StateRunning}, nil, "running", "Status: running", false, true, false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + got := menuStatus(tc.service, tc.err, tc.connection) + want := MenuStatus{Label: tc.label, CanStart: tc.start, CanStop: tc.stop, AutoStart: tc.auto, StartupKnown: tc.known} + if got != want { + t.Fatalf("status=%#v, want %#v", got, want) + } + }) + } +} + +func TestTrayMenuHasBannerAndSingleAutoToggle_HP_WINTRAY_06(t *testing.T) { + for _, automatic := range []bool{false, true} { + items := trayMenu(MenuStatus{Label: "Status: running", AutoStart: automatic, StartupKnown: true, CanStop: true}) + if items[0].Action != 0 || !items[0].Disabled || items[0].Label != "Status: running" { + t.Fatalf("status is clickable: %#v", items[0]) + } + count := 0 + for _, item := range items { + if item.Action == ActionStatus || item.Action == ActionRestartService || item.Action == ActionSetManual || strings.Contains(item.Label, "automatically") || strings.Contains(item.Label, "manually") { + t.Fatalf("obsolete menu item: %#v", item) + } + if item.Label == "Auto start" { + count++ + if item.Checked != automatic || item.Disabled { + t.Fatalf("bad toggle: %#v", item) + } + } + } + if count != 1 { + t.Fatalf("auto start count=%d", count) + } + if automaticAction(automatic) == ActionSetAutomatic && automatic || automaticAction(automatic) == ActionSetManual && !automatic { + t.Fatal("toggle does not invert confirmed SCM state") + } + } +} diff --git a/internal/client/windowstray/tray_windows.go b/internal/client/windowstray/tray_windows.go index 3196aab..6481421 100644 --- a/internal/client/windowstray/tray_windows.go +++ b/internal/client/windowstray/tray_windows.go @@ -23,6 +23,7 @@ import ( "unicode/utf8" "unsafe" + "github.com/rvbox/rvbox/internal/client/windowsservice" winapi "golang.org/x/sys/windows" ) @@ -30,6 +31,7 @@ const ( wmDestroy = 0x0002 wmClose = 0x0010 wmCommand = 0x0111 + wmTimer = 0x0113 wmRButtonUp = 0x0205 wmLButtonDblClick = 0x0203 wmApp = 0x8000 @@ -45,6 +47,9 @@ const ( trayTPMRightBtn = 0x0002 trayMFString = 0x00000000 trayMFSeparator = 0x00000800 + trayMFDisabled = 0x00000001 + trayMFChecked = 0x00000008 + trayMFByPosition = 0x00000400 traySWHide = 0 trayIDIApplication = 32512 trayIDCArrow = 32512 @@ -69,6 +74,7 @@ var ( procLoadCursor = user32Tray.NewProc("LoadCursorW") procCreatePopup = user32Tray.NewProc("CreatePopupMenu") procAppendMenu = user32Tray.NewProc("AppendMenuW") + procModifyMenu = user32Tray.NewProc("ModifyMenuW") procTrackPopup = user32Tray.NewProc("TrackPopupMenu") procDestroyMenu = user32Tray.NewProc("DestroyMenu") procGetCursorPos = user32Tray.NewProc("GetCursorPos") @@ -78,6 +84,8 @@ var ( procShellNotify = shell32Tray.NewProc("Shell_NotifyIconW") procShellIconRect = shell32Tray.NewProc("Shell_NotifyIconGetRect") procFindWindow = user32Tray.NewProc("FindWindowW") + procSetTimer = user32Tray.NewProc("SetTimer") + procKillTimer = user32Tray.NewProc("KillTimer") trayCallback = syscall.NewCallback(trayWindowProc) trayWindows sync.Map // hwnd -> *trayWindow taskbarCreatedMessage uint32 @@ -128,27 +136,32 @@ type trayIconData struct { } type trayWindow struct { - hwnd uintptr - icon trayIconData - class *uint16 - tooltip string - output io.Writer - closeOnce sync.Once - ctx context.Context - responses chan trayActionResult - pending bool // UI-thread owned; at most one bounded request at a time. + hwnd uintptr + icon trayIconData + class *uint16 + tooltip string + output io.Writer + closeOnce sync.Once + ctx context.Context + responses chan trayActionResult + pending bool // UI-thread owned; at most one background status request. + logPending bool + configPath string + status MenuStatus + menu uintptr } type trayActionResult struct { action Action response Frame err error + status *MenuStatus } // Run starts one notification icon for the current logged-in session. It // returns when the icon is closed, the service becomes unavailable, or ctx is // cancelled; none of those outcomes affect the machine-wide service. -func Run(ctx context.Context, output io.Writer) error { +func Run(ctx context.Context, configPath string, output io.Writer) error { mutex, err := acquireTrayMutex() if err != nil { return err @@ -160,7 +173,7 @@ func Run(ctx context.Context, output io.Writer) error { done := make(chan error, 1) // Icon creation never waits for the daemon or the network. Status refresh // is asynchronous after the icon exists, including when the service is down. - go runTrayMessageLoop(ctx, output, "RVBox service", ready, done) + go runTrayMessageLoop(ctx, output, "Status: checking", ready, done, configPath) var window *trayWindow select { case window = <-ready: @@ -209,7 +222,7 @@ func acquireTrayMutex() (winapi.Handle, error) { return mutex, nil } -func runTrayMessageLoop(ctx context.Context, output io.Writer, tooltip string, ready chan<- *trayWindow, done chan<- error) { +func runTrayMessageLoop(ctx context.Context, output io.Writer, tooltip string, ready chan<- *trayWindow, done chan<- error, configPath string) { runtime.LockOSThread() defer runtime.UnlockOSThread() if ctx.Err() != nil { @@ -240,7 +253,7 @@ func runTrayMessageLoop(ctx context.Context, output io.Writer, tooltip string, r done <- callErr return } - window := &trayWindow{hwnd: hwnd, class: className, tooltip: tooltip, output: output, ctx: ctx, responses: make(chan trayActionResult, 1)} + window := &trayWindow{hwnd: hwnd, class: className, tooltip: tooltip, output: output, ctx: ctx, responses: make(chan trayActionResult, 2), status: MenuStatus{Label: "Status: checking"}, configPath: configPath} window.icon = trayIconData{CbSize: uint32(unsafe.Sizeof(trayIconData{})), HWnd: hwnd, UID: trayIconID, UFlags: trayNIFMessage | trayNIFIcon | trayNIFTip, UCallbackMessage: trayMessage, HIcon: icon} copy(window.icon.Tip[:len(window.icon.Tip)-1], winapi.StringToUTF16(tooltip)) trayWindows.Store(hwnd, window) @@ -256,6 +269,8 @@ func runTrayMessageLoop(ctx context.Context, output io.Writer, tooltip string, r _, _, _ = procShowWindow.Call(hwnd, traySWHide) ready <- window window.action(ActionStatus) + _, _, _ = procSetTimer.Call(hwnd, 1, 2000, 0) + defer procKillTimer.Call(hwnd, 1) for { var message trayMessageRecord result, _, getErr := procGetMessage.Call(uintptr(unsafe.Pointer(&message)), 0, 0, 0) @@ -290,7 +305,16 @@ func trayWindowProc(hwnd uintptr, message uint32, wParam, lParam uintptr) uintpt return 0 case wmCommand: if window != nil { - window.action(Action(uint16(wParam))) + action := Action(uint16(wParam)) + if action == ActionSetAutomatic { + action = automaticAction(window.status.AutoStart) + } + window.action(action) + } + return 0 + case wmTimer: + if window != nil { + window.action(ActionStatus) } return 0 case trayResponse: @@ -339,40 +363,95 @@ func (window *trayWindow) showMenu() { return } defer procDestroyMenu.Call(menu) - add := func(action Action, label string) { - text, _ := winapi.UTF16PtrFromString(label) - procAppendMenu.Call(menu, trayMFString, uintptr(action), uintptr(unsafe.Pointer(text))) + window.menu = menu + defer func() { window.menu = 0 }() + for _, item := range trayMenu(window.status) { + flags, text := menuItemFlags(item) + procAppendMenu.Call(menu, flags, uintptr(item.Action), uintptr(unsafe.Pointer(text))) } - add(ActionStatus, "Status") - add(ActionOpenConfig, "Open config") - add(ActionOpenLog, "Open log") - procAppendMenu.Call(menu, trayMFSeparator, 0, 0) - add(ActionStartService, "Start service") - add(ActionStopService, "Stop service") - add(ActionRestartService, "Restart service") - add(ActionSetAutomatic, "Start automatically") - add(ActionSetManual, "Start manually") - procAppendMenu.Call(menu, trayMFSeparator, 0, 0) - add(ActionExitTray, "Exit") + window.action(ActionStatus) var point trayPoint procGetCursorPos.Call(uintptr(unsafe.Pointer(&point))) procSetForeground.Call(window.hwnd) procTrackPopup.Call(menu, trayTPMRightBtn, uintptr(point.X), uintptr(point.Y), 0, window.hwnd, 0) } +func menuItemFlags(item menuItem) (uintptr, *uint16) { + if item.Separator { + return trayMFSeparator, nil + } + flags := uintptr(trayMFString) + if item.Disabled { + flags |= trayMFDisabled + } + if item.Checked { + flags |= trayMFChecked + } + text, _ := winapi.UTF16PtrFromString(item.Label) + return flags, text +} + +func (window *trayWindow) refreshMenu() { + if window.menu == 0 { + return + } + for index, item := range trayMenu(window.status) { + flags, text := menuItemFlags(item) + procModifyMenu.Call(window.menu, uintptr(index), flags|trayMFByPosition, uintptr(item.Action), uintptr(unsafe.Pointer(text))) + } +} + func (window *trayWindow) action(action Action) { if action == ActionExitTray { _, _, _ = procDestroyWindow.Call(window.hwnd) return } - if window.pending { + if action == ActionOpenConfig { + if err := openExactPath(window.configPath); err != nil { + window.setTooltip("RVBox: could not open config") + } + return + } + if isServiceMutation(action) { + // Service control remains a narrow UAC helper. It does not depend on + // a live pipe, and a background status poll cannot swallow this click. + if err := runElevatedServiceAction(action, window.configPath); err != nil && !errors.Is(err, winapi.ERROR_CANCELLED) { + window.setTooltip("RVBox: service action could not start") + } + window.action(ActionStatus) + return + } + if action == ActionStatus { + if window.pending { + return + } + window.pending = true + } else if action == ActionOpenLog { + if window.logPending { + return + } + window.logPending = true + } else { return } - window.pending = true go func() { - response, err := Request(window.ctx, Frame{Action: action}) + result := trayActionResult{action: action} + if action == ActionStatus { + service, err := windowsservice.Query() + connection := "" + if err == nil && service.State == windowsservice.StateRunning { + response, requestErr := Request(window.ctx, Frame{Action: ActionStatus}) + if requestErr == nil { + connection = string(response.Payload) + } + } + status := menuStatus(service, err, connection) + result.status = &status + } else { + result.response, result.err = Request(window.ctx, Frame{Action: action}) + } select { - case window.responses <- trayActionResult{action: action, response: response, err: err}: + case window.responses <- result: _, _, _ = procPostMessage.Call(window.hwnd, trayResponse, 0, 0) case <-window.ctx.Done(): } @@ -386,27 +465,20 @@ func (window *trayWindow) applyResponse() { default: return } - window.pending = false action, response := result.action, result.response + if action == ActionStatus && result.status != nil { + window.pending = false + window.status = *result.status + window.setTooltip("RVBox — " + window.status.Label) + window.refreshMenu() + return + } + window.logPending = false if result.err != nil { - if isServiceMutation(action) { - // A stopped service has no pipe to answer Start. The same narrow - // UAC helper is valid both for absent IPC and denied authorization. - if err := runElevatedServiceAction(action); err == nil { - window.setTooltip("RVBox elevation requested") - return - } - } window.setTooltip("RVBox service unavailable") return } - if isServiceMutation(action) && strings.HasPrefix(string(response.Payload), "error:") { - if err := runElevatedServiceAction(action); err == nil { - window.setTooltip("RVBox elevation requested") - return - } - } - if action == ActionOpenConfig || action == ActionOpenLog { + if action == ActionOpenLog { if err := openExactPath(string(response.Payload)); err != nil { window.setTooltip("RVBox open failed") } @@ -478,7 +550,7 @@ func isServiceMutation(action Action) bool { // remains the authorization boundary; this helper only replays the enum as a // canonical rvbox mode under an administrator token when the tray's filtered // token cannot mutate SCM state directly. -func runElevatedServiceAction(action Action) error { +func runElevatedServiceAction(action Action, configPath string) error { mode := "" switch action { case ActionStartService: @@ -498,13 +570,6 @@ func runElevatedServiceAction(action Action) error { if err != nil { return err } - configPath := "" - for index := 0; index+1 < len(os.Args); index++ { - if os.Args[index] == "--config" { - configPath = os.Args[index+1] - break - } - } if configPath == "" { return errors.New("tray config path is unavailable") } diff --git a/test/coverage.toml b/test/coverage.toml index 2c7da0c..922a6dc 100644 --- a/test/coverage.toml +++ b/test/coverage.toml @@ -1,5 +1,47 @@ version = 1 +[[requirements]] +id = "HP-WINTRAY-05" +layer = "unit" +status = "implemented" +tests = ["internal/client/windowstray/status_test.go:TestTrayStatusUsesSCMAndConnection_HP_WINTRAY_05"] + +[[requirements]] +id = "HP-WINTRAY-06" +layer = "unit" +status = "implemented" +tests = ["internal/client/windowstray/status_test.go:TestTrayMenuHasBannerAndSingleAutoToggle_HP_WINTRAY_06"] + +[[requirements]] +id = "HP-WINTRAY-07" +layer = "integration" +status = "implemented" +tests = ["internal/client/windowstray/native_windows_test.go:TestNativeTrayReadOnlyServiceQuery_HP_WINTRAY_07"] + +[[requirements]] +id = "HP-WINTRAY-08" +layer = "integration" +status = "implemented" +tests = ["internal/client/windowstray/native_windows_test.go:TestNativeTrayMenuFlagsAndRefresh_HP_WINTRAY_08"] + +[[requirements]] +id = "HP-WINCLI-08" +layer = "integration" +status = "implemented" +tests = ["cmd/rvbox/installer_windows_test.go:TestInstallerConfigACLAllowsOriginalUser_HP_WINCLI_08"] + +[[requirements]] +id = "HP-WINCLI-09" +layer = "unit" +status = "implemented" +tests = ["cmd/rvbox/tray_status_windows_test.go:TestTrayConnectionStatusWithoutObservability_HP_WINCLI_09"] + +[[requirements]] +id = "BH-WINCLI-02" +layer = "unit" +status = "implemented" +tests = ["cmd/rvbox/installer_windows_test.go:TestInstallerConfigUserSIDValidation_BH_WINCLI_02"] + [[requirements]] id = "HP-CFG-01" layer = "unit"