diff --git a/PENDING-ISSUES.md b/PENDING-ISSUES.md new file mode 100644 index 0000000..4a172bb --- /dev/null +++ b/PENDING-ISSUES.md @@ -0,0 +1,65 @@ +# Pending issues + +## RVBox Windows commands do not reliably show GUI prompts + +When a GUI uninstaller is launched through `rvc run --shell cmd`, its dialog may +not appear on the user's desktop. This was observed with IDA Freeware 7.0 and +HandBrake 1.6.1: their registered uninstallers ran through RVBox without a +visible confirmation dialog, and the apps remained installed after the +non-elevated attempts. + +The command status selected the affected desktop's active user in session 1, with the +matching user SID. That rules out a simple Session 0 selection error, but does +not establish that the process shares Explorer's visible desktop. The Windows +launcher in the affected build started the shell with `STARTF_USESHOWWINDOW` +and `SW_HIDE`, then `CREATE_NEW_CONSOLE`, with `STARTUPINFO.lpDesktop` unset. +That hid the shell and did not explicitly select the user's visible desktop. +Microsoft's [STARTUPINFO documentation](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-startupinfoa) +describes these startup fields as controlling the process's window station, +desktop, and initial window appearance; [ShowWindow](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow) +uses the supplied startup state for an application's first window. + +The repository's [GUI test guidance](docs/testing.md:249) explicitly says that +matching session IDs alone do not prove a process shares Explorer's window +station and desktop. Together, the hidden startup state and inherited desktop +are the strongest code-based explanation for the missing dialogs. No screenshot +or direct window-station inspection was available to confirm which condition +prevented these specific uninstaller windows from appearing. + +The RVBox troubleshooting guide also says GUI work needs the intended +interactive session and desktop, and that token/session data alone is +insufficient ([troubleshooting.md](skills/rvbox/references/troubleshooting.md:57)). +Treat a successful command lifecycle as evidence that the launched process +exited, not that an uninstall completed. Verify the app's executable and +uninstall registration afterward. + +### Implemented correction; native acceptance pending + +The corrected launcher explicitly selects `winsta0\default` for active-user, +active-user-elevated, and active-system, including the command shell and signal +helper. The authenticated launcher reports its observed desktop and verifies +existing GUI access under the selected token before user code is prepared. +Session 0 contexts retain their noninteractive desktop. No desktop ACLs or +user-global terminal preferences are changed. + +Shells now use `CREATE_NO_WINDOW` with `SW_SHOWNORMAL`, keeping console +suppression independent of GUI startup appearance. Existing output pipes, +suspended launch/authorization, Job containment, and TERM helper remain in use. +Console-event delivery needs native acceptance on this headless-console route. + +Portable policy tests and Windows compilation cover the new path. Native tests +exercise actual desktop access, real GUI creation through the launcher, and +CTRL_BREAK observed by a controlled root PowerShell handler. The native harness +stages/checksums the self-contained GUI probe and checks visible-window evidence +for active-user, active-user-elevated, and active-system. These tests have not +been executed while Helium is offline; compilation is not a native pass. + +Keep this issue open until the actual Windows desktop probe and the affected +uninstallers have been retested. The earlier `SW_HIDE` on the shell was a +plausible contributor, not proof that every GUI descendant inherited it. +Validate a real window and the application's final effect, including elevated +requirements, rather than inferring success from session/SID or process exit. +See [the advanced GUI guide](skills/rvbox/references/windows-gui.md) for `/wait`, +the diagnostic script, locked/background windows, Job lifetime and shell-policy +limits. Vendor unattended flags remain an optional workflow, not proof of a +working interactive launch path. diff --git a/docs/README.md b/docs/README.md index 6873747..594ddcb 100644 --- a/docs/README.md +++ b/docs/README.md @@ -26,6 +26,8 @@ Read the documents in this order: backup/restore, upgrade, and incident response. 11. [Portable RVBox operations skill](../skills/rvbox/SKILL.md) — deployment discovery, verified CLI syntax, Control API access, and troubleshooting. +12. [Pending implementation issues](../PENDING-ISSUES.md) — observed gaps and + fixes still awaiting native acceptance. The wire authority is in [`../protos/rvbox/v1`](../protos/rvbox/v1): `common.proto` contains shared data types, `agent.proto` contains the diff --git a/docs/implementation-plan.v1.md b/docs/implementation-plan.v1.md index a2833f5..7323640 100644 --- a/docs/implementation-plan.v1.md +++ b/docs/implementation-plan.v1.md @@ -2216,9 +2216,9 @@ effective token SID the required access. `FILETIME`, token SID, session ID, and generation before sending any launch material. 4. The launcher opens only the verified pipes and creates the requested shell - suspended with `CREATE_NEW_CONSOLE`, `CREATE_SUSPENDED`, + suspended with `CREATE_NO_WINDOW`, `CREATE_SUSPENDED`, `CREATE_UNICODE_ENVIRONMENT`, and `EXTENDED_STARTUPINFO_PRESENT`. Use - `STARTF_USESHOWWINDOW`/`SW_HIDE`; pass only standard-I/O handles with + `STARTF_USESHOWWINDOW`/`SW_SHOWNORMAL`; pass only standard-I/O handles with `PROC_THREAD_ATTRIBUTE_HANDLE_LIST`. Job membership propagates because breakaway is disabled. Report shell PID/creation time and wait for release. 5. Persist and flush `launch_prepared` with requested elevation, attempted/ @@ -2258,9 +2258,10 @@ bounded result. It receives no Job or stdio handle. A helper creation or attach failure is recorded and may use the verified direct attach fallback before the configured grace-period Job escalation. -Do not combine `CREATE_NEW_PROCESS_GROUP` with `CREATE_NEW_CONSOLE`: Windows -ignores the former, and it is unnecessary because every command owns a distinct -hidden console. For TERM, start a short-lived private signal-helper mode of the +Do not combine `CREATE_NO_WINDOW` with `CREATE_NEW_CONSOLE` or +`DETACHED_PROCESS`: these override headless creation. A new process-group flag +is unnecessary because every command owns a distinct headless console. For TERM, +start a short-lived private signal-helper mode of the same canonical `rvbox.exe` using the command's effective token/session. Pass the target identity through a separate unpredictable, PID/token/session-verified local named pipe rather than inherited cross-session handles or the command @@ -2272,6 +2273,15 @@ installs a control handler that consumes its own CTRL_BREAK, then calls that command's console receive it. It reports a checksum-framed result and detaches. The helper receives neither the Job handle nor command stdio. +Detach any pre-existing helper console before attachment, and install a real +Ctrl+C/Ctrl+Break-consuming callback after attachment resets the handler table. +`SetConsoleCtrlHandler(NULL, TRUE)` protects only against Ctrl+C and cannot +protect a sender broadcasting Ctrl+Break to its own attached console. Detach +before removing the callback. Serialize the service's process-wide direct attach +fallback; primary signal helpers already run in separate processes. Native +headless-console acceptance must prove both target-handler observation and +survival of the helper through its authenticated delivery report. + Apply `PROC_THREAD_ATTRIBUTE_HANDLE_LIST` to every same-session child creation. Every database, log, listener, Job, unrelated pipe, and SCM handle is non- inheritable. Length/type/generation/checksum-frame launcher/signal-helper @@ -2304,6 +2314,41 @@ Linux-only wait reasons. ### 7.5 Windows desktop host and lifecycle +For active-user, active-user-elevated and active-system, derive the fixed +`winsta0\default` target from the verified identity/session and set `lpDesktop` +on the per-command launcher, shell and signal helper. Reject active contexts +with Session 0 and local contexts with nonzero sessions. No caller-supplied +desktop option is required. Session 0 contexts keep their noninteractive target. +On a locked OS thread in the selected-session launcher, inspect actual process +window station/thread desktop (`GetProcessWindowStation`, `GetThreadDesktop`, +`GetUserObjectInformationW`), validate WinSta0/Default, and open non-inheritable +station/desktop handles to check existing GUI access under that token. Close +only owned handles. Never rewrite global desktop ACLs or switch secure desktops. +Report the observed path in the private authenticated hello and validate it in +the service. Use bounded `launcherFrameAbort` diagnostics for preparation errors +so the service records actionable rejection instead of an unexplained EOF. + +Create command shells suspended with `CREATE_NO_WINDOW`, normal Unicode/env/ +extended-startup handling, redirected stdio, explicit desktop and +`STARTF_USESHOWWINDOW`/`SW_SHOWNORMAL`. Do not combine headless creation with +`CREATE_NEW_CONSOLE` or `DETACHED_PROCESS`, and do not use `SW_HIDE` on command +shells. This separates console suppression from GUI child appearance while +retaining the private console's verified CTRL_BREAK route. Preserve inherited +handle allowlists, kill-on-close/non-breakaway Jobs and durable launch barriers. + +Test identity/desktop policy and bad targets portably. Native acceptance must +observe real windows (including input-desktop match and no console window) on +normal and elevated paths, and independently prove CTRL_BREAK reaches a +controlled root PowerShell handler without forced termination. The native +Compose/SCM harness must stage/checksum the bundled self-contained GUI probe +and assert its report for active-user, active-user-elevated and forced +active-system routes. Keep no-user and ambiguous-session behavior unchanged. +Cross-compilation and parser checks are not native acceptance. Keep the pending +issue open until physical Windows/fixture tests pass, including the affected +GUI uninstallers. Document `/wait`/Job lifetime, broker handoff, locked desktops, +foreground restrictions and retained shell-policy/profile defaults in the +RVBox skill's advanced guide; do not promise arbitrary applications show UI. + Build the executable with the Windows GUI subsystem so service/helper/tray modes never flash an unwanted console. Human-invoked `--help`, `--check-config`, install, uninstall, and configuration modes call diff --git a/docs/platform-and-operations.md b/docs/platform-and-operations.md index 2d52b02..ccf29e2 100644 --- a/docs/platform-and-operations.md +++ b/docs/platform-and-operations.md @@ -226,6 +226,25 @@ desktop: a display, audio, or other session-scoped command may therefore fail normally in Session 0. Selection fallback is not a promise that the requested operation is meaningful in the resulting context. +Active contexts explicitly launch the per-command helper, shell and TERM +helper on `winsta0\default` within the selected token's session. The helper +checks its actual station/desktop and existing access for GUI creation before +preparing user code; it reports that path over the authenticated channel. +Failures become bounded launch diagnostics. Do not broaden desktop ACLs, +switch to Winlogon, or change identity after launch preparation. Session 0 +fallbacks retain their noninteractive desktop. + +The command shell uses `CREATE_NO_WINDOW` plus `SW_SHOWNORMAL`: console +suppression is independent of GUI startup visibility. The private headless +console retains the verified CTRL_BREAK helper route, subject to native TERM +acceptance. Standard handles, Job containment, suspension and authorization +barriers are unchanged. Desktop placement does not guarantee foreground focus +or force an application to create UI. Locked Default desktops become visible +after unlocking. Use `start "" /wait APP` for supervised GUI apps; a root shell +that exits can close the command's Job and terminate remaining owned children. +Explorer/single-instance handoffs may reach an existing process outside that +Job. See [Windows GUI workflows](../skills/rvbox/references/windows-gui.md). + For normal `active_user`, use the filtered token when Windows supplies one. If an administrator is logged in with only a full token (for example traditional UAC is disabled), create and verify a LUA-style restricted medium-integrity @@ -264,9 +283,9 @@ session ID, and launch generation; a same-user process racing for a pipe cannot satisfy that complete identity. The launcher opens only those pipes, creates the selected shell suspended in -its own dedicated console with `CREATE_NEW_CONSOLE`, `CREATE_SUSPENDED`, +its own dedicated headless console with `CREATE_NO_WINDOW`, `CREATE_SUSPENDED`, `CREATE_UNICODE_ENVIRONMENT`, and `EXTENDED_STARTUPINFO_PRESENT`, and uses -`STARTF_USESHOWWINDOW`/`SW_HIDE`. It inherits only the explicit standard-I/O +`STARTF_USESHOWWINDOW`/`SW_SHOWNORMAL`. It inherits only the explicit standard-I/O handles through `PROC_THREAD_ATTRIBUTE_HANDLE_LIST`. Non-breakaway Job membership propagates from the launcher. It reports the suspended shell PID and creation `FILETIME` and waits for the service's release/watchdog channel. @@ -290,8 +309,9 @@ or running shell, and descendants. Recovery never kills by persisted PID alone. Job Object limits enforce requested profiles and `KILL_ON_JOB_CLOSE` protects against lost supervision. -Do not request `CREATE_NEW_PROCESS_GROUP` with `CREATE_NEW_CONSOLE`; Windows -ignores that combination. TERM instead launches a short-lived private mode of +Each command owns a headless console; no new process-group flag is needed. +Do not combine `CREATE_NO_WINDOW` with `CREATE_NEW_CONSOLE` or +`DETACHED_PROCESS`, which override it. TERM launches a short-lived private mode of the same `rvbox.exe` under the command's effective token and session. It uses a separate PID-verified local named-pipe handshake, not inherited cross-session handles, to receive the target PID/creation-time/generation. It attaches to the @@ -301,7 +321,11 @@ CTRL_BREAK, and calls root exit, select and birth-verify a live PID from the Job list. Because each command owns its console, this does not address an unrelated command. The helper detaches and reports delivery; it receives neither the Job handle nor -command stdio. +command stdio. Before attaching, detach any helper-owned console. Register an +actual Ctrl+C/Ctrl+Break handler after attachment, since attaching resets handler +state; `SetConsoleCtrlHandler(NULL, TRUE)` ignores only Ctrl+C. Detach before +removing that protection. Serialize the process-wide console-attachment fallback +inside the service so concurrent requests cannot attach to different consoles. Root-process exit begins the same drain grace period. Completion waits for the Job Object to reach zero active processes; after the grace period RVBox diff --git a/docs/testing.md b/docs/testing.md index 5ce585d..7a233cd 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -216,6 +216,55 @@ Windows console test executable. Inspect the persisted typed loss event itself when checking evidence: the existing server's GetOutput summary does not yet derive its incomplete flag/stream details from every incoming peer loss marker. +### Interactive command desktop and visible-window regression checks + +`HP-DESKTOP-01` and `BH-DESKTOP-01/02` cover every context's desktop placement, +nonzero-session requirements, rejection of secure/other desktop targets, and +bounded launcher-abort diagnostics. The Windows implementation sets the fixed +interactive target on launcher/shell/signal helper, checks the actual desktop +and GUI access in that selected session, and creates a headless command console +with normal GUI startup visibility. No public protocol fields are added. + +`HP-DESKTOP-02` probes actual desktop access from an interactive test thread. +Native `HP-DESKTOP-03/04` require a disposable LocalSystem test process, one +usable unlocked active desktop, and `RVBOX_NATIVE_GUI_PROBE` pointing to the +bundled `skills/rvbox/scripts/windows_gui_probe.ps1` at a user-readable guest +path. Put the console test executable itself at a user-readable test-only path. +It dispatches its child launcher/signal-helper to the production entrypoints. +Build in Docker: + +```sh +docker compose -f deploy/compose.yaml run --rm toolchain \ + env CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go test -c \ + -o .test-runs/RUN/supervisor.test.exe ./internal/client/supervisor/windows +``` + +Run native `TestNativeLauncherShowsGUIOnSelectedDesktop` and +`TestNativeHeadlessConsoleStillReceivesTERM` through the fixture's LocalSystem +route with `-test.v -test.timeout 120s`; a skip is not native evidence. The +former uses normal CMD-wrapper execution at both privilege levels and requires +the probe's actual window-visible/input-desktop report. The latter prepares +PowerShell directly through the production launcher (avoiding cmd batch-abort +semantics), waits for its controlled handler, then requires authenticated TERM +delivery without forced escalation plus `RVBOX_CTRL_BREAK_OBSERVED` output. +The fixture uses process-scoped PowerShell execution policy only for its known +diagnostic script; no machine/user policy is rewritten. + +`scripts/windows/native-test run --run-id ID` now automatically bundles, +transfers and checksums the probe, and executes it through the production-shaped +Linux Compose server and SCM daemon for active-user, active-user-elevated, and +forced active-system. It requires remote success plus JSON evidence of a real +window on WinSta0/Default/input Default and a hidden console, retaining +`gui-CONTEXT.log/.stat` in that run's artifact directory. The prepared console +must be unlocked; Session 0/locked/ambiguous sessions do not substitute for this +test. Existing collect/reset/purge workflows include the probe and its artifacts. + +For a physical-machine visual test, use the standalone probe and commands in +[the RVBox advanced GUI guide](../skills/rvbox/references/windows-gui.md). +Installer v12 and probe/native tests remain pending Windows execution while +Helium is offline. PowerShell syntax/C# binding compilation and Windows test +cross-compilation do not prove the affected uninstallers' dialogs now appear. + ### Focused native tray and installer regression checks `internal/client/windowstray/native_windows_test.go` contains real Win32 tests, diff --git a/internal/client/supervisor/windows/desktop.go b/internal/client/supervisor/windows/desktop.go new file mode 100644 index 0000000..d14f804 --- /dev/null +++ b/internal/client/supervisor/windows/desktop.go @@ -0,0 +1,43 @@ +package windows + +import ( + "fmt" + "strings" + + "github.com/rvbox/rvbox/internal/client/supervisor" +) + +const interactiveDesktop = `winsta0\default` + +// Desktop placement follows the selected identity, never a caller-supplied +// desktop name. Session 0 contexts keep their noninteractive desktop. +func desktopForIdentity(identity supervisor.EffectiveIdentity) (string, error) { + switch ExecutionContext(identity.Context) { + case ContextActiveUser, ContextActiveUserElevated, ContextActiveSystem: + if identity.SessionID == 0 { + return "", fmt.Errorf("active execution context has no interactive session") + } + return interactiveDesktop, nil + case ContextLocalService, ContextLocalSystem: + if identity.SessionID != 0 { + return "", fmt.Errorf("local execution context unexpectedly targets session %d", identity.SessionID) + } + return "", nil + default: + return "", fmt.Errorf("unknown Windows execution context %q", identity.Context) + } +} + +func validateInteractiveDesktop(desktop string) error { + if !strings.EqualFold(desktop, interactiveDesktop) { + return fmt.Errorf("interactive desktop mismatch: got %q, want %q", desktop, interactiveDesktop) + } + return nil +} + +func launcherAbortError(payload []byte) error { + if len(payload) == 0 || len(payload) > 4096 { + return fmt.Errorf("launcher preparation failed without a valid diagnostic") + } + return fmt.Errorf("launcher preparation failed: %s", payload) +} diff --git a/internal/client/supervisor/windows/desktop_test.go b/internal/client/supervisor/windows/desktop_test.go new file mode 100644 index 0000000..30cca00 --- /dev/null +++ b/internal/client/supervisor/windows/desktop_test.go @@ -0,0 +1,55 @@ +package windows + +import ( + "strings" + "testing" + + "github.com/rvbox/rvbox/internal/client/supervisor" +) + +func TestDesktopPlacementFollowsSelectedIdentity_HP_DESKTOP_01(t *testing.T) { + for _, context := range []ExecutionContext{ContextActiveUser, ContextActiveUserElevated, ContextActiveSystem} { + for _, sessionID := range []uint32{1, 7, 42} { + desktop, err := desktopForIdentity(supervisor.EffectiveIdentity{Context: string(context), SessionID: sessionID}) + if err != nil || desktop != interactiveDesktop { + t.Fatalf("%s/%d: desktop=%q err=%v", context, sessionID, desktop, err) + } + } + } + for _, context := range []ExecutionContext{ContextLocalService, ContextLocalSystem} { + desktop, err := desktopForIdentity(supervisor.EffectiveIdentity{Context: string(context)}) + if err != nil || desktop != "" { + t.Fatalf("%s: desktop=%q err=%v", context, desktop, err) + } + } +} + +func TestDesktopRejectsWrongSessionAndSecureTargets_BH_DESKTOP_01(t *testing.T) { + for _, identity := range []supervisor.EffectiveIdentity{ + {Context: string(ContextActiveUser)}, {Context: string(ContextActiveUserElevated)}, {Context: string(ContextActiveSystem)}, + {Context: string(ContextLocalService), SessionID: 1}, {Context: string(ContextLocalSystem), SessionID: 1}, {Context: "unknown", SessionID: 1}, + } { + if _, err := desktopForIdentity(identity); err == nil { + t.Fatalf("invalid identity accepted: %+v", identity) + } + } + for _, target := range []string{"", `winsta0\winlogon`, `winsta0\screensaver`, `Service-0x0-3e7$\default`, `winsta0\other`, `winsta0\default\extra`} { + if err := validateInteractiveDesktop(target); err == nil { + t.Fatalf("wrong desktop accepted: %q", target) + } + } + if err := validateInteractiveDesktop(`WinSta0\Default`); err != nil { + t.Fatal(err) + } +} + +func TestDesktopFailureDiagnosticIsBounded_BH_DESKTOP_02(t *testing.T) { + if err := launcherAbortError([]byte("interactive desktop access: Access is denied.")); !strings.Contains(err.Error(), "Access is denied") { + t.Fatal(err) + } + for _, payload := range [][]byte{nil, make([]byte, 4097)} { + if err := launcherAbortError(payload); !strings.Contains(err.Error(), "without a valid diagnostic") { + t.Fatal(err) + } + } +} diff --git a/internal/client/supervisor/windows/desktop_windows.go b/internal/client/supervisor/windows/desktop_windows.go new file mode 100644 index 0000000..3da1625 --- /dev/null +++ b/internal/client/supervisor/windows/desktop_windows.go @@ -0,0 +1,98 @@ +//go:build windows + +package windows + +import ( + "fmt" + "unsafe" + + winapi "golang.org/x/sys/windows" +) + +var ( + desktopUser32 = winapi.NewLazySystemDLL("user32.dll") + procProcessWindowStation = desktopUser32.NewProc("GetProcessWindowStation") + procThreadDesktop = desktopUser32.NewProc("GetThreadDesktop") + procUserObjectInformation = desktopUser32.NewProc("GetUserObjectInformationW") + procOpenWindowStation = desktopUser32.NewProc("OpenWindowStationW") + procCloseWindowStation = desktopUser32.NewProc("CloseWindowStation") + procOpenDesktop = desktopUser32.NewProc("OpenDesktopW") + procCloseDesktop = desktopUser32.NewProc("CloseDesktop") +) + +func desktopPointer(desktop string) *uint16 { + if desktop == "" { + return nil + } + value, _ := winapi.UTF16PtrFromString(desktop) + return value +} + +func userObjectName(handle uintptr) (string, error) { + var name [256]uint16 + var needed uint32 + result, _, err := procUserObjectInformation.Call(handle, 2 /* UOI_NAME */, uintptr(unsafe.Pointer(&name[0])), unsafe.Sizeof(name), uintptr(unsafe.Pointer(&needed))) + if result == 0 { + return "", fmt.Errorf("read window station/desktop name: %w", err) + } + if needed < 2 || needed > uint32(unsafe.Sizeof(name)) { + return "", fmt.Errorf("invalid window station/desktop name size %d", needed) + } + return winapi.UTF16ToString(name[:]), nil +} + +// Check access in the selected-session helper, not Session 0's service. Never +// broaden desktop ACLs or switch to Winlogon/the secure input desktop. A locked +// session can open Default now and display its UI when the user unlocks. +func verifyCurrentInteractiveDesktop(sessionID uint32) (string, error) { + if sessionID == 0 { + return "", nil + } + station, _, err := procProcessWindowStation.Call() + if station == 0 { + return "", fmt.Errorf("get process window station: %w", err) + } + desktop, _, err := procThreadDesktop.Call(uintptr(winapi.GetCurrentThreadId())) + if desktop == 0 { + return "", fmt.Errorf("get thread desktop: %w", err) + } + stationName, err := userObjectName(station) + if err != nil { + return "", err + } + desktopName, err := userObjectName(desktop) + if err != nil { + return "", err + } + path := stationName + `\` + desktopName + if err := validateInteractiveDesktop(path); err != nil { + return "", err + } + // Open non-inheritable handles to check existing logon-token access. The + // handles returned by GetProcessWindowStation/GetThreadDesktop are borrowed. + stationHandle, _, err := procOpenWindowStation.Call(uintptr(unsafe.Pointer(desktopPointer("winsta0"))), 0, + 0x0002|0x0020 /* READATTRIBUTES | ACCESSGLOBALATOMS */) + if stationHandle == 0 { + return "", fmt.Errorf("interactive window station access: %w", err) + } + defer procCloseWindowStation.Call(stationHandle) + desktopHandle, _, err := procOpenDesktop.Call(uintptr(unsafe.Pointer(desktopPointer("default"))), 0, 0, + 0x0001|0x0002|0x0004|0x0080 /* READOBJECTS | CREATEWINDOW | CREATEMENU | WRITEOBJECTS */) + if desktopHandle == 0 { + return "", fmt.Errorf("interactive desktop access: %w", err) + } + defer procCloseDesktop.Call(desktopHandle) + return path, nil +} + +func commandStartup(stdin, stdout, stderr winapi.Handle, desktop string) (winapi.StartupInfoEx, uint32) { + startup := winapi.StartupInfoEx{StartupInfo: winapi.StartupInfo{ + Cb: uint32(unsafe.Sizeof(winapi.StartupInfoEx{})), Desktop: desktopPointer(desktop), + Flags: winapi.STARTF_USESTDHANDLES | winapi.STARTF_USESHOWWINDOW, ShowWindow: winapi.SW_SHOWNORMAL, + StdInput: stdin, StdOutput: stdout, StdErr: stderr, + }} + // A private headless console does not ask GUI descendants to hide. Keep + // this distinct from DETACHED_PROCESS so the TERM helper can still attach. + flags := uint32(winapi.CREATE_NO_WINDOW | winapi.CREATE_SUSPENDED | winapi.CREATE_UNICODE_ENVIRONMENT | winapi.EXTENDED_STARTUPINFO_PRESENT) + return startup, flags +} diff --git a/internal/client/supervisor/windows/desktop_windows_test.go b/internal/client/supervisor/windows/desktop_windows_test.go new file mode 100644 index 0000000..4da1844 --- /dev/null +++ b/internal/client/supervisor/windows/desktop_windows_test.go @@ -0,0 +1,253 @@ +//go:build windows + +package windows + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + rvboxv1 "github.com/rvbox/rvbox/gen/go/rvbox/v1" + "github.com/rvbox/rvbox/internal/client/supervisor" + "github.com/rvbox/rvbox/internal/domain" + winapi "golang.org/x/sys/windows" +) + +// Native fixture children execute the production launcher/helper entrypoints. +// This dispatcher exists only in the test executable, never the release image. +func TestMain(m *testing.M) { + if len(os.Args) == 4 && os.Args[2] == "--channel" { + var err error + switch os.Args[1] { + case "--launcher": + err = RunLauncher(context.Background(), os.Args[3]) + case "--signal-helper": + err = RunSignalHelper(context.Background(), os.Args[3]) + default: + os.Exit(m.Run()) + } + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + os.Exit(0) + } + os.Exit(m.Run()) +} + +func TestNativeDesktopAccessOnActualThread_HP_DESKTOP_02(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + var sessionID uint32 + if err := winapi.ProcessIdToSessionId(winapi.GetCurrentProcessId(), &sessionID); err != nil { + t.Fatal(err) + } + if sessionID == 0 { + t.Skip("requires an interactive desktop; Session 0 is a separate route") + } + path, err := verifyCurrentInteractiveDesktop(sessionID) + if err != nil { + t.Fatal(err) + } + if err := validateInteractiveDesktop(path); err != nil { + t.Fatal(err) + } +} + +// This fixture lane requires LocalSystem (SCM/service route), one usable active +// desktop, and the bundled PowerShell probe readable by that user. Run it in the +// disposable native fixture, not by changing an ordinary user's service state. +func desktopFixture(t *testing.T, elevated bool) (*execSupervisor, string, string) { + t.Helper() + var token winapi.Token + if err := winapi.OpenProcessToken(winapi.CurrentProcess(), winapi.TOKEN_QUERY, &token); err != nil { + t.Fatal(err) + } + user, err := token.GetTokenUser() + _ = token.Close() + if err != nil { + t.Fatal(err) + } + if user.User.Sid.String() != securitySystemRID { + t.Skip("requires LocalSystem native fixture process") + } + probe := os.Getenv("RVBOX_NATIVE_GUI_PROBE") + if probe == "" { + t.Skip("set RVBOX_NATIVE_GUI_PROBE to the bundled windows_gui_probe.ps1") + } + if !filepath.IsAbs(probe) { + t.Fatal("GUI probe path must be absolute") + } + if info, err := os.Lstat(probe); err != nil || !info.Mode().IsRegular() { + t.Fatalf("GUI probe must be a readable regular file: %v", err) + } + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + root := os.Getenv("SystemRoot") + if root == "" { + root = `C:\Windows` + } + manager := newExecSupervisor(NativeOptions{ExecutablePath: executable, Shells: ShellPaths{CMD: filepath.Join(root, "System32", "cmd.exe"), PowerShell: filepath.Join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")}, WindowsTermGrace: 3 * time.Second}) + selected, identity, err := manager.selectToken(elevated) + if err != nil { + t.Fatal(err) + } + _ = selected.Close() + if identity.SessionID == 0 { + t.Skip("requires one usable active session, not a Session 0 fallback") + } + directory := t.TempDir() + // Both levels are owned by this t.TempDir fixture. Only SYSTEM and the + // selected effective SID receive access, including wrapper-file traversal. + for _, path := range []string{filepath.Dir(directory), directory} { + sd, err := winapi.SecurityDescriptorFromString(fmt.Sprintf("D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;%s)", identity.UserSID)) + if err != nil { + t.Fatal(err) + } + dacl, _, err := sd.DACL() + if err != nil { + t.Fatal(err) + } + if err := winapi.SetNamedSecurityInfo(path, winapi.SE_FILE_OBJECT, winapi.DACL_SECURITY_INFORMATION|winapi.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, dacl, nil); err != nil { + t.Fatal(err) + } + } + t.Cleanup(func() { _ = manager.StopAll(context.Background()) }) + return manager, directory, probe +} + +func desktopProbeProcess(t *testing.T, manager *execSupervisor, directory, probe string, elevated, consoleOnly bool) (supervisor.Process, context.Context) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + t.Cleanup(cancel) + args := []string{manager.options.Shells.PowerShell, "-NoLogo", "-NoProfile", "-STA", "-ExecutionPolicy", "Bypass", "-File", probe, "-Seconds", "2"} + if consoleOnly { + args[len(args)-1] = "25" + args = append(args, "-ConsoleOnly") + } + command, err := BuildCommandLine(args) + if err != nil { + t.Fatal(err) + } + issue, err := domain.NewUUIDv7() + if err != nil { + t.Fatal(err) + } + spec := supervisor.StartSpec{IssueUUID: issue, CommandRevision: 1, WorkingDirectory: directory, Execution: &rvboxv1.ExecutionSpec{ShellType: rvboxv1.ShellType_SHELL_CMD, Elevated: elevated, Source: &rvboxv1.ExecutionSpec_CommandText{CommandText: "@" + command}}} + var process supervisor.Process + if consoleOnly { + // Isolate console-event delivery from cmd's own batch-abort behavior. + // The actual launcher still prepares this root shell suspended, puts it + // in the Job, and uses the production authenticated TERM helper. + token, identity, tokenErr := manager.selectToken(elevated) + if tokenErr != nil { + t.Fatal(tokenErr) + } + defer token.Close() + base, envErr := token.Environ(false) + if envErr != nil { + t.Fatal(envErr) + } + environment, envErr := BuildEnvironmentBlock(parseEnvironment(base), nil) + if envErr != nil { + t.Fatal(envErr) + } + process, err = manager.startViaLauncher(ctx, spec, token, identity, LaunchPlan{ApplicationName: args[0], CommandLine: command, WorkingDirectory: directory, Environment: environment}, nil) + } else { + process, err = manager.Start(ctx, spec) + } + if err != nil { + t.Fatal(err) + } + if process.Identity().SessionID == 0 { + t.Fatal("native GUI route unexpectedly fell back to Session 0") + } + if err := process.Release(ctx); err != nil { + t.Fatal(err) + } + return process, ctx +} + +func TestNativeLauncherShowsGUIOnSelectedDesktop_HP_DESKTOP_03(t *testing.T) { + for _, elevated := range []bool{false, true} { + t.Run(fmt.Sprintf("elevated=%v", elevated), func(t *testing.T) { + manager, directory, probe := desktopFixture(t, elevated) + process, ctx := desktopProbeProcess(t, manager, directory, probe, elevated, false) + var output strings.Builder + for { + chunk, err := process.ReadOutput(ctx) + if errors.Is(err, io.EOF) { + break + } + if err != nil { + t.Fatal(err) + } + output.Write(chunk.Data) + } + status, err := process.Wait(ctx) + if err != nil || status.Code != 0 { + t.Fatalf("probe exit=%v err=%v output=%s", status, err, output.String()) + } + var report struct { + SessionID uint32 `json:"session_id"` + Station string `json:"window_station"` + Desktop string `json:"desktop"` + Input string `json:"input_desktop"` + Visible bool `json:"window_observed"` + ConsoleVisible bool `json:"console_window_visible"` + } + found := false + for _, line := range strings.Split(output.String(), "\n") { + if strings.HasPrefix(strings.TrimSpace(line), "{") { + if err := json.Unmarshal([]byte(line), &report); err != nil { + t.Fatal(err) + } + found = true + } + } + if !found || !report.Visible || report.ConsoleVisible || report.SessionID != process.Identity().SessionID || !strings.EqualFold(report.Station+`\`+report.Desktop, interactiveDesktop) || !strings.EqualFold(report.Input, "default") { + t.Fatalf("GUI probe did not observe an interactive window: %+v output=%s", report, output.String()) + } + }) + } +} + +func TestNativeHeadlessConsoleStillReceivesTERM_HP_DESKTOP_04(t *testing.T) { + manager, directory, probe := desktopFixture(t, false) + process, ctx := desktopProbeProcess(t, manager, directory, probe, false, true) + var output strings.Builder + for !strings.Contains(output.String(), "RVBOX_CONSOLE_READY") { + chunk, err := process.ReadOutput(ctx) + if err != nil { + t.Fatalf("console never became ready: %v %s", err, output.String()) + } + output.Write(chunk.Data) + } + outcome, err := manager.Signal(ctx, process, supervisor.SignalTerm) + if err != nil || !outcome.Delivered || outcome.Escalated { + t.Fatalf("TERM lost native console delivery: %+v err=%v", outcome, err) + } + for { + chunk, err := process.ReadOutput(ctx) + if errors.Is(err, io.EOF) { + break + } + if err != nil { + t.Fatal(err) + } + output.Write(chunk.Data) + } + if !strings.Contains(output.String(), "RVBOX_CTRL_BREAK_OBSERVED") { + t.Fatalf("TERM never reached the registered handler: %s", output.String()) + } +} diff --git a/internal/client/supervisor/windows/launcher_windows.go b/internal/client/supervisor/windows/launcher_windows.go index 1c9a647..b7c0f62 100644 --- a/internal/client/supervisor/windows/launcher_windows.go +++ b/internal/client/supervisor/windows/launcher_windows.go @@ -11,6 +11,7 @@ import ( "io" "os" "os/exec" + "runtime" "strings" "sync" "syscall" @@ -242,6 +243,13 @@ func openLauncherPipe(channel, suffix string, access uint32) (*os.File, error) { } func (manager *execSupervisor) startViaLauncher(ctx context.Context, spec supervisor.StartSpec, token winapi.Token, identity supervisor.EffectiveIdentity, launch LaunchPlan, cleanup func()) (supervisor.Process, error) { + desktop, err := desktopForIdentity(identity) + if err != nil { + if cleanup != nil { + cleanup() + } + return nil, err + } pipes, err := newLauncherPipes(identity.UserSID) if err != nil { if cleanup != nil { @@ -299,6 +307,7 @@ func (manager *execSupervisor) startViaLauncher(ctx context.Context, spec superv return nil, err } startup := winapi.StartupInfoEx{StartupInfo: winapi.StartupInfo{Cb: uint32(unsafe.Sizeof(winapi.StartupInfoEx{}))}} + startup.Desktop = desktopPointer(desktop) var launcherInfo winapi.ProcessInformation flags := uint32(winapi.CREATE_SUSPENDED | winapi.CREATE_UNICODE_ENVIRONMENT | winapi.EXTENDED_STARTUPINFO_PRESENT | winapi.CREATE_NO_WINDOW) if err := winapi.CreateProcessAsUser(token, launcherApplication, &launcherCommandUTF16[0], nil, nil, false, flags, nil, nil, &startup.StartupInfo, &launcherInfo); err != nil { @@ -334,6 +343,9 @@ func (manager *execSupervisor) startViaLauncher(ctx context.Context, spec superv return nil, fmt.Errorf("read launcher hello: %w", err) } if frame.Kind != launcherFrameHello { + if frame.Kind == launcherFrameAbort { + return nil, launcherAbortError(frame.Payload) + } return nil, errors.New("launcher did not send hello first") } var hello launcherHello @@ -343,6 +355,11 @@ func (manager *execSupervisor) startViaLauncher(ctx context.Context, spec superv if hello.PID != expected.PID || hello.Creation != expected.Creation || hello.SessionID != expected.SessionID || hello.Effective != expected.UserSID { return nil, errors.New("launcher hello identity mismatch") } + if desktop != "" { + if err := validateInteractiveDesktop(hello.Desktop); err != nil { + return nil, err + } + } requestPayload, err := marshalLauncherPayload(launcherRequest{ApplicationName: launch.ApplicationName, CommandLine: launch.CommandLine, WorkingDirectory: launch.WorkingDirectory, Environment: launch.Environment}) if err != nil { return nil, err @@ -355,6 +372,9 @@ func (manager *execSupervisor) startViaLauncher(ctx context.Context, spec superv return nil, fmt.Errorf("read shell preparation: %w", err) } if frame.Kind != launcherFrameShellPrepared { + if frame.Kind == launcherFrameAbort { + return nil, launcherAbortError(frame.Payload) + } return nil, errors.New("launcher did not prepare a shell") } var prepared launcherShellPrepared @@ -457,7 +477,9 @@ func (manager *execSupervisor) startViaLauncher(ctx context.Context, spec superv // private pipes, reports its immutable identity, creates the requested shell // suspended, and waits for the service's durable release frame before running // any command code. -func RunLauncher(_ context.Context, channel string) error { +func RunLauncher(_ context.Context, channel string) (resultErr error) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() generation, err := launcherGeneration(channel) if err != nil { return err @@ -467,6 +489,15 @@ func RunLauncher(_ context.Context, channel string) error { return err } defer control.Close() + defer func() { + if resultErr != nil { + detail := resultErr.Error() + if len(detail) > 4096 { + detail = detail[:4096] + } + _ = writeLauncherFrame(control, launcherFrame{Kind: launcherFrameAbort, Generation: generation, Payload: []byte(detail)}) + } + }() stdin, err := openLauncherPipe(channel, "stdin", winapi.GENERIC_READ) if err != nil { return err @@ -496,11 +527,15 @@ func RunLauncher(_ context.Context, channel string) error { if err != nil { return err } + desktop, err := verifyCurrentInteractiveDesktop(sessionID) + if err != nil { + return err + } creation, err := processCreation(winapi.CurrentProcess()) if err != nil { return err } - helloPayload, err := marshalLauncherPayload(launcherHello{PID: winapi.GetCurrentProcessId(), Creation: creation, SessionID: sessionID, Effective: user.User.Sid.String()}) + helloPayload, err := marshalLauncherPayload(launcherHello{PID: winapi.GetCurrentProcessId(), Creation: creation, SessionID: sessionID, Effective: user.User.Sid.String(), Desktop: desktop}) if err != nil { return err } @@ -550,14 +585,13 @@ func RunLauncher(_ context.Context, channel string) error { if err := attributes.Update(winapi.PROC_THREAD_ATTRIBUTE_HANDLE_LIST, unsafe.Pointer(&childHandles[0]), uintptr(len(childHandles))*unsafe.Sizeof(childHandles[0])); err != nil { return err } - startup := winapi.StartupInfoEx{StartupInfo: winapi.StartupInfo{Cb: uint32(unsafe.Sizeof(winapi.StartupInfoEx{})), Flags: winapi.STARTF_USESTDHANDLES | winapi.STARTF_USESHOWWINDOW, ShowWindow: winapi.SW_HIDE, StdInput: childHandles[0], StdOutput: childHandles[1], StdErr: childHandles[2]}} + startup, flags := commandStartup(childHandles[0], childHandles[1], childHandles[2], desktop) startup.ProcThreadAttributeList = attributes.List() var shellInfo winapi.ProcessInformation var environment *uint16 if len(request.Environment) > 0 { environment = &request.Environment[0] } - flags := uint32(winapi.CREATE_NEW_CONSOLE | winapi.CREATE_SUSPENDED | winapi.CREATE_UNICODE_ENVIRONMENT | winapi.EXTENDED_STARTUPINFO_PRESENT) if err := winapi.CreateProcess(application, &commandLine[0], nil, nil, true, flags, environment, workingDirectory, &startup.StartupInfo, &shellInfo); err != nil { return fmt.Errorf("create suspended shell: %w", err) } @@ -664,6 +698,10 @@ func openSignalPipe(channel string) (*os.File, error) { } func runSignalHelper(ctx context.Context, executable string, token winapi.Token, identity supervisor.EffectiveIdentity, targetPID uint32, targetCreation uint64) (bool, error) { + desktop, err := desktopForIdentity(identity) + if err != nil { + return false, err + } if executable == "" { var err error executable, err = os.Executable() @@ -695,6 +733,7 @@ func runSignalHelper(ctx context.Context, executable string, token winapi.Token, return false, err } startup := winapi.StartupInfo{Cb: uint32(unsafe.Sizeof(winapi.StartupInfo{}))} + startup.Desktop = desktopPointer(desktop) var info winapi.ProcessInformation flags := uint32(winapi.CREATE_NO_WINDOW | winapi.CREATE_UNICODE_ENVIRONMENT) if err := winapi.CreateProcessAsUser(token, application, &commandUTF16[0], nil, nil, false, flags, nil, nil, &startup, &info); err != nil { diff --git a/internal/client/supervisor/windows/launcher_wire.go b/internal/client/supervisor/windows/launcher_wire.go index edf1b0c..235d54e 100644 --- a/internal/client/supervisor/windows/launcher_wire.go +++ b/internal/client/supervisor/windows/launcher_wire.go @@ -14,6 +14,7 @@ type launcherHello struct { Creation uint64 `json:"creation"` SessionID uint32 `json:"session_id"` Effective string `json:"effective_sid"` + Desktop string `json:"desktop,omitempty"` } type launcherRequest struct { diff --git a/internal/client/supervisor/windows/native_windows.go b/internal/client/supervisor/windows/native_windows.go index fca7b77..6a7b3bf 100644 --- a/internal/client/supervisor/windows/native_windows.go +++ b/internal/client/supervisor/windows/native_windows.go @@ -13,6 +13,7 @@ import ( "fmt" "os" "strings" + "sync" "syscall" "time" "unsafe" @@ -41,6 +42,13 @@ var ( procFreeConsole = kernel32.NewProc("FreeConsole") procGenerateCtrlEvent = kernel32.NewProc("GenerateConsoleCtrlEvent") procSetCtrlHandler = kernel32.NewProc("SetConsoleCtrlHandler") + consoleControlMu sync.Mutex + ignoreOwnConsoleEvent = winapi.NewCallback(func(event uint32) uintptr { + if event == 0 || event == 1 { + return 1 + } // CTRL_C_EVENT / CTRL_BREAK_EVENT. + return 0 + }) ) func stdinLineEnding() []byte { return []byte{'\r', '\n'} } @@ -851,16 +859,30 @@ func sendControlBreak(pid uint32) (bool, error) { if pid == 0 { return false, errors.New("command has no verified console PID") } + // Console attachment is process-wide. The service fallback must serialize + // concurrent requests; the normal route uses a separate helper process. + consoleControlMu.Lock() + defer consoleControlMu.Unlock() + // A console-subsystem test/helper may have its own headless console. It + // must detach before attaching to the verified command's private console. + procFreeConsole.Call() if result, _, err := procAttachConsole.Call(uintptr(pid)); result == 0 { if err == syscall.Errno(0) { err = syscall.GetLastError() } return false, err } - defer procFreeConsole.Call() - // Prevent the service/helper itself from acting on the generated event. - procSetCtrlHandler.Call(0, 1) - defer procSetCtrlHandler.Call(0, 0) + // NULL/TRUE ignores only Ctrl+C, not the Ctrl+Break sent below. Install a + // real handler after attachment (which resets the handler table), then + // detach before removing it so our own broadcast cannot terminate us. + if result, _, err := procSetCtrlHandler.Call(ignoreOwnConsoleEvent, 1); result == 0 { + procFreeConsole.Call() + return false, fmt.Errorf("protect console signal helper: %w", err) + } + defer func() { + procFreeConsole.Call() + procSetCtrlHandler.Call(ignoreOwnConsoleEvent, 0) + }() result, _, err := procGenerateCtrlEvent.Call(1 /* CTRL_BREAK_EVENT */, 0) if result == 0 { if err == syscall.Errno(0) { diff --git a/scripts/windows/build-test-bundle b/scripts/windows/build-test-bundle index f0d1a2b..d36e71c 100755 --- a/scripts/windows/build-test-bundle +++ b/scripts/windows/build-test-bundle @@ -10,7 +10,7 @@ usage() { usage: scripts/windows/build-test-bundle --run-id ID --config FILE [--ca FILE] [--no-build] [--native-fixture] Builds bin/rvbox.exe in the pinned Docker toolchain, then creates exactly: - .test-runs/ID/windows-bundle/{rvbox.exe,client.toml[,ca.pem],manifest.sha256} + .test-runs/ID/windows-bundle/{rvbox.exe,client.toml,windows_gui_probe.ps1[,ca.pem],manifest.sha256} The bundle is for the resettable native-test fixture only. The config must use the target guest paths and the declared test nginx endpoint. Existing bundles @@ -75,6 +75,7 @@ trap 'rmdir "$bundle" 2>/dev/null || true' INT TERM HUP install -m 700 "$binary" "$bundle/rvbox.exe" install -m 600 "$config" "$bundle/client.toml" +install -m 644 "$repo_root/skills/rvbox/scripts/windows_gui_probe.ps1" "$bundle/windows_gui_probe.ps1" if [ -n "$ca" ]; then install -m 600 "$ca" "$bundle/ca.pem"; fi commit=$(git -C "$repo_root" rev-parse HEAD) @@ -82,7 +83,7 @@ commit=$(git -C "$repo_root" rev-parse HEAD) printf 'run_id=%s\n' "$run_id" printf 'git_commit=%s\n' "$commit" printf 'native_fixture=%s\n' "$native_fixture" - (cd "$bundle" && sha256sum rvbox.exe client.toml ${ca:+ca.pem}) + (cd "$bundle" && sha256sum rvbox.exe client.toml windows_gui_probe.ps1 ${ca:+ca.pem}) } >"$bundle/manifest.sha256" chmod 600 "$bundle/manifest.sha256" diff --git a/scripts/windows/native-test b/scripts/windows/native-test index 237a9d7..d1aa306 100755 --- a/scripts/windows/native-test +++ b/scripts/windows/native-test @@ -188,6 +188,37 @@ assert_stdin_close() { fail "stdin command did not reach terminal success" } +assert_gui() { + gui_label=$1 + gui_elevated=$2 + gui_probe_command="@powershell.exe -NoLogo -NoProfile -STA -ExecutionPolicy Bypass -File \"C:/ProgramData/RVBox/test-runs/$run_id/windows_gui_probe.ps1\" -Seconds 2" + if [ "$gui_elevated" = yes ]; then + gui_result=$(rvc run --elevated --shell cmd "$client_id" "$gui_probe_command" 2>&1) || fail "GUI probe RPC failed: $gui_result" + else + gui_result=$(rvc run --shell cmd "$client_id" "$gui_probe_command" 2>&1) || fail "GUI probe RPC failed: $gui_result" + fi + printf '%s\n' "$gui_result" >"$fixture_dir/gui-$gui_label.log" + gui_issue=$(printf '%s\n' "$gui_result" | awk 'NR == 1 { print $1 }') + case $gui_issue in ????????-????-7???-????-????????????) ;; *) fail "GUI probe returned invalid issue UUID: $gui_result" ;; esac + gui_state=$(rvc stat "$client_id" "$gui_issue") || fail "GUI probe status failed" + printf '%s\n' "$gui_state" >"$fixture_dir/gui-$gui_label.stat" + printf '%s\n' "$gui_state" | grep -q 'lifecycle=COMMAND_SUCCEEDED' || fail "GUI probe failed: $gui_state (see gui-$gui_label.log)" + printf '%s\n' "$gui_result" | python3 -c ' +import json, sys +reports = [json.loads(line) for line in sys.stdin if line.lstrip().startswith("{")] +if len(reports) != 1: + raise SystemExit("GUI probe did not return exactly one report") +r = reports[0] +if not (r.get("window_observed") and r.get("session_id", 0) > 0 and + r.get("window_station", "").lower() == "winsta0" and + r.get("desktop", "").lower() == "default" and + r.get("input_desktop", "").lower() == "default" and + r.get("console_window_visible") is False): + raise SystemExit("GUI probe did not observe a real window on the unlocked input desktop") +' || fail "GUI visibility/desktop assertion failed; inspect gui-$gui_label.log" + printf 'passed gui-%s issue=%s\n' "$gui_label" "$gui_issue" +} + assert_signal_term() { issued=$(rvc run --background --shell cmd "$client_id" 'ping -t 127.0.0.1 >NUL' 2>&1) || fail "signal command admission failed: $issued" issue=$(printf '%s\n' "$issued" | awk 'NR == 1 { print $1 }') @@ -300,10 +331,13 @@ case $action in assert_signal_term assert_server_restart_reconnect assert_context active-user no active-user + assert_gui active-user no assert_context active-user-elevated yes active-user-elevated + assert_gui active-user-elevated yes "$repo_root/scripts/windows/test-host" run --run-id "$run_id" --fail-contexts ACTIVE_USER_ELEVATED wait_client assert_context active-system yes active-system + assert_gui active-system yes "$repo_root/scripts/windows/test-host" run --run-id "$run_id" --fail-contexts ACTIVE_USER_ELEVATED,ACTIVE_SYSTEM wait_client assert_context local-system-active-fallback yes local-system diff --git a/scripts/windows/test-host b/scripts/windows/test-host index 2d3ac13..e9d8750 100755 --- a/scripts/windows/test-host +++ b/scripts/windows/test-host @@ -550,6 +550,10 @@ case "$action" in require_lease VBoxManage guestcontrol "$vm" --username "$guest_user" --passwordfile "$password_file" \ copyto "$host_stage/client.toml" "$guest_root\\client.toml" /dev/null | awk '{print \$1}'" 2>/dev/null || true) if [ "$local_exe_hash" = "$remote_exe_hash" ]; then @@ -863,11 +872,7 @@ case $action in accelerated_stage || fail "accelerated executable transfer failed" trap 'if [ -n "$accelerated_artifact" ]; then rm -f "$accelerated_artifact"; fi' EXIT HUP INT TERM fi - if [ -f "$bundle/ca.pem" ]; then - remote_hashes=$(ssh -o BatchMode=yes "$RVBOX_TEST_VBOX_HOST" "cd '$host_stage' && sha256sum rvbox.exe client.toml ca.pem" 2>/dev/null || true) - else - remote_hashes=$(ssh -o BatchMode=yes "$RVBOX_TEST_VBOX_HOST" "cd '$host_stage' && sha256sum rvbox.exe client.toml" 2>/dev/null || true) - fi + remote_hashes=$(ssh -o BatchMode=yes "$RVBOX_TEST_VBOX_HOST" "cd '$host_stage' && sha256sum $bundle_files" 2>/dev/null || true) [ "$local_hashes" = "$remote_hashes" ] || fail "bundle transfer did not reach the expected SHA-256 manifest" printf 'verified transfer_sha256 run_id=%s\n%s\n' "$run_id" "$local_hashes" remote stage diff --git a/skills/rvbox/SKILL.md b/skills/rvbox/SKILL.md index 88e646b..4c8c01e 100644 --- a/skills/rvbox/SKILL.md +++ b/skills/rvbox/SKILL.md @@ -79,6 +79,8 @@ Flags precede positional arguments, including the verbs after `storage` and historical output, resumable follow, JSON-RPC, pagination, and structured errors. - [Troubleshooting](references/troubleshooting.md): transport failures, queued work, Windows identity/session/GUI issues, PowerShell policy, quotas, and recovery. +- [Windows GUI and desktop workflows](references/windows-gui.md): interactive + defaults, application lifetime, real-window probes, and missing-dialog diagnosis. An optional Python 3 helper, [scripts/request_id.py](scripts/request_id.py), prints a canonical UUIDv7 using only the standard library. It performs no RPC. diff --git a/skills/rvbox/references/troubleshooting.md b/skills/rvbox/references/troubleshooting.md index bafb5bf..60c9dc9 100644 --- a/skills/rvbox/references/troubleshooting.md +++ b/skills/rvbox/references/troubleshooting.md @@ -19,6 +19,7 @@ initial evidence; do not restart services or resubmit work merely to inspect it. | Socket permission denied | Run as the existing socket owner through the deployment route; inspect directory traversal and mount permissions. Do not chmod the control socket world-accessible. | | Client missing or NOT_FOUND | List all client pages; verify the exact registered ID and server instance. A hostname assumption or wrong Compose project can select different state. Retention can also remove command history. | | Disconnected / OFFLINE / UNAVAILABLE | Separate server recovery from client connectivity. Inspect SCM, WSS hostname/path, proxy WebSocket upgrade, certificate/time/CA, DNS, reconnect logs, and pending instance conflicts. Missing optional HTTP health is not proof of a stopped daemon. | +| Repeated `signal command ...: command is not running` | An older client disconnects on a late signal instead of persisting its rejection. Upgrade the client while retaining config/spool/history; corrected builds acknowledge the signal without disconnecting. Do not wipe state or reissue the original command. | | QUEUED persists | Check connection, supported shell, queue/running capacity, acceptance events, and queue expiry. Queuing does not promise execution, and queue TTL is not a runtime timeout. | | CLI deadline / broken stream | Work may still run. Query the captured issue and resume history via the API. For uncertain admission, retry only with the same request ID and payload. | | CLI exit 0 but task failed | Inspect remote terminal lifecycle, rejection/detail, and output. A successful follow stream is not a successful process. | @@ -60,6 +61,14 @@ follow the effective token. A single-owner laptop may have a split admin token, but do not assume it. If a UI does not appear, verify both token/session and window station/desktop; a process listing alone is insufficient. +Builds containing the interactive-desktop fix explicitly target +`winsta0\default` for active-user, active-user-elevated, and active-system. +They verify the launcher's actual desktop/access, use a headless command console, +and request normal GUI startup visibility. Session 0 routes remain +noninteractive. See [Windows GUI workflows](windows-gui.md) for a bundled +visible-window probe, `/wait` examples, and limits involving locks, focus, +privileges, shell policy, and applications that hand off to an existing process. + ### Opening folders and Explorer exit code 1 For shell folder opening, use `start "" "%USERPROFILE%"` through `--shell cmd`. diff --git a/skills/rvbox/references/windows-gui.md b/skills/rvbox/references/windows-gui.md new file mode 100644 index 0000000..7a12b83 --- /dev/null +++ b/skills/rvbox/references/windows-gui.md @@ -0,0 +1,119 @@ +# Windows GUI and desktop workflows + +## Contents + +- Defaults and limits +- Launch an application and retain its lifetime +- Verify a real window +- Diagnose missing dialogs + +## Defaults and limits + +Use the established `rv` deployment prefix from [deployment.md](deployment.md). +Inspect the client's version and effective execution identity; older builds +may lack these defaults. With the interactive-desktop fix, active-user, +active-user-elevated, and active-system launch the helper and shell on that +session's `winsta0\default`. The helper checks actual window-station/desktop +names and GUI access under its selected token before preparing user code. +Desktop ACLs are not broadened. The command console is headless and GUI startup +uses normal visibility. No extra per-request desktop/window flags are needed. + +Normal requests use the active user's non-elevated token when a usable session +exists. Request `--elevated` only when the operation needs it, and inspect the +effective context: active-system uses SYSTEM, including its profile/network +identity; local-system/local-service in Session 0 cannot display on the user's +desktop. The tray need not be running and does not own execution. + +A window can appear behind other windows, remain on Default until the user +unlocks, or stay with the original session after a session switch. RVBox does +not force foreground focus, switch secure desktops, or manufacture application +dialogs. A program may run silently, fail initialization, or delegate to an +existing process. Successful admission/process exit is not visible-task success. + +The target token supplies base environment/profile identity; request environment +overrides and explicit CWD still apply. Do not assume the CWD is the user's home +or that a running Explorer's private environment is cloned. PowerShell wrappers +retain `-NoLogo -NoProfile -NonInteractive -File` and normal execution-policy +checks. `-NonInteractive` rejects host `Read-Host`/confirmation prompts; it does +not prohibit a native application or WinForms script from displaying its UI. +There is captured stdin/stdout/stderr, not an interactive terminal/PTY. + +## Launch an application and retain its lifetime + +For an application RVBox should supervise until it exits: + +```sh +rv run --background --shell cmd CLIENT \ + 'start "" /wait "C:\Program Files\Example\Example.exe"' +``` + +The empty quoted argument is cmd's window title; `/wait` keeps the command +alive for the launched application. Background admission avoids keeping a +CLI follow open beyond its 30-second deadline. Save the issue UUID and inspect +the application's window plus `rv stat CLIENT ISSUE_UUID`. + +RVBox owns a non-breakaway Job, including ordinary descendants. An asynchronous +`start` can let the root shell exit and close its Job, terminating still-owned +children. Use `/wait` for supervised GUI applications. A single-instance app or +Explorer may hand off to an existing process outside that Job; `/wait` then +tracks only the new launcher, not the existing process or its windows. Killing +the command is not a general way to close delegated windows. + +To open an existing user's folder through Explorer: + +```sh +rv run --shell cmd CLIENT 'start "" "%USERPROFILE%\Pictures"' +``` + +Confirm the folder actually opened. Direct `explorer.exe PATH` can return `1` +after successfully handing off; preserve that raw result instead of globally +treating `1` as success. See [Explorer troubleshooting](troubleshooting.md#opening-folders-and-explorer-exit-code-1). + +## Verify a real window + +The bundled [windows_gui_probe.ps1](../scripts/windows_gui_probe.ps1) uses inbox +Windows PowerShell/.NET and installs nothing. Place it at a readable target +Windows path, then launch it through the same RVBox route being diagnosed: + +```sh +rv run --shell cmd CLIENT \ + 'powershell.exe -NoLogo -NoProfile -STA -ExecutionPolicy Bypass -File "C:\Users\Public\RVBoxGUIProbe.ps1" -Seconds 8' +``` + +This deliberate diagnostic invocation sets process-only execution policy; it +does not change registry/Group Policy. Keep managed-policy failures explicit. +The script opens a small window for 1–25 seconds and emits JSON containing the +actual session/user SID, station, desktop, input desktop, observed window +visibility, console visibility, and startup show state. Require remote success, +`window_observed=true`, `WinSta0`/`Default`, matching intended session, input +desktop `Default`, and `console_window_visible=false`. Confirm the window on +the desktop when doing visual acceptance. Exit `2` means at least one of those +checks failed; read the JSON, including `input_desktop_error` for locked or +inaccessible input desktops. The SID is diagnostic output, not a stored skill +credential. The `-ConsoleOnly` mode instead waits for CTRL_BREAK and reports +`RVBOX_CONSOLE_READY` / `RVBOX_CTRL_BREAK_OBSERVED`; reserve it for controlled +TERM testing against the owned command. + +## Diagnose missing dialogs + +1. Verify selected session, effective SID/context, requested elevation, and + launch rejection. Matching user/session alone does not prove correct desktop + placement. A `launcher preparation failed` desktop/access message identifies + a pre-launch failure; correct the account/session/access prerequisites rather + than granting broad desktop permissions or silently changing identities. +2. Unlock and view the intended user's desktop. Run the probe through RVBox; + distinguish failure to create/show a window from an unfocused/background one. +3. If the probe succeeds, inspect the application's actual command line, + unattended flags, elevation requirement, logs, policy/initialization errors, + and single-instance handoff. For uninstallers, verify executable/registry + removal independently; a completed wrapper or missing prompt proves neither. +4. Check shell policy, CWD, environment and quoting. Use uploaded scripts for + complex commands. Test the exact invocation locally as the same user when + needed; do not silently change privileges or resubmit uncertain side effects. +5. For an ordinary GUI app killed immediately, inspect `/wait`, root-shell exit, + Job termination and handoff. Keep request/issue IDs and failure output before + retrying. Retest with the fixed client; compare actual windows, not just PIDs. + +Windows references: [interactive process creation](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessasuserw), +[console allocation semantics](https://github.com/microsoft/terminal/blob/main/doc/specs/%237335%20-%20Console%20Allocation%20Policy.md), +[foreground restrictions](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setforegroundwindow). diff --git a/skills/rvbox/scripts/windows_gui_probe.ps1 b/skills/rvbox/scripts/windows_gui_probe.ps1 new file mode 100644 index 0000000..77ddb85 --- /dev/null +++ b/skills/rvbox/scripts/windows_gui_probe.ps1 @@ -0,0 +1,106 @@ +# Self-contained diagnostic: real window/desktop visibility, or console TERM. +# Uses Windows PowerShell 5.1 / .NET already present; installs nothing. +param( + [ValidateRange(1, 25)][int]$Seconds = 8, + [switch]$ConsoleOnly +) +$ErrorActionPreference = 'Stop' +Add-Type -TypeDefinition @' +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +namespace RVBoxDesktopProbe { + public static class Native { + [StructLayout(LayoutKind.Sequential)] public struct StartupInfo { + public uint cb; public IntPtr reserved, desktop, title; + public uint x,y,xSize,ySize,xChars,yChars,fill,flags; + public ushort showWindow,reservedBytes; + public IntPtr reservedData,input,output,error; + } + [DllImport("kernel32.dll")] public static extern void GetStartupInfoW(out StartupInfo value); + [DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId(); + [DllImport("kernel32.dll")] public static extern IntPtr GetConsoleWindow(); + [DllImport("kernel32.dll")] public static extern uint GetConsoleCP(); + [DllImport("user32.dll")] public static extern IntPtr GetProcessWindowStation(); + [DllImport("user32.dll")] public static extern IntPtr GetThreadDesktop(uint thread); + [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window); + [DllImport("user32.dll", SetLastError=true)] public static extern IntPtr OpenInputDesktop(uint flags, bool inherit, uint access); + [DllImport("user32.dll")] public static extern bool CloseDesktop(IntPtr desktop); + [DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true)] + static extern bool GetUserObjectInformationW(IntPtr handle,int index,StringBuilder value,uint size,out uint needed); + public static string Name(IntPtr handle) { + var value = new StringBuilder(256); uint needed; + if (handle == IntPtr.Zero || !GetUserObjectInformationW(handle,2,value,512,out needed)) + throw new Win32Exception(Marshal.GetLastWin32Error()); + return value.ToString(); + } + delegate bool Handler(uint code); + [DllImport("kernel32.dll",SetLastError=true)] static extern bool SetConsoleCtrlHandler(Handler handler,bool add); + public static bool WaitForBreak(int milliseconds) { + using (var received = new ManualResetEvent(false)) { + Handler handler = delegate(uint code) { if (code != 1) return false; received.Set(); return true; }; + if (!SetConsoleCtrlHandler(handler,true)) throw new Win32Exception(Marshal.GetLastWin32Error()); + try { + Console.WriteLine("RVBOX_CONSOLE_READY"); Console.Out.Flush(); + bool seen = received.WaitOne(milliseconds); + Console.WriteLine(seen ? "RVBOX_CTRL_BREAK_OBSERVED" : "RVBOX_CTRL_BREAK_TIMEOUT"); Console.Out.Flush(); + return seen; + } finally { SetConsoleCtrlHandler(handler,false); GC.KeepAlive(handler); } + } + } + } +} +'@ +if ($ConsoleOnly) { + if ([RVBoxDesktopProbe.Native]::WaitForBreak($Seconds * 1000)) { exit 0 } + exit 2 +} +Add-Type -AssemblyName System.Windows.Forms +$startup = New-Object RVBoxDesktopProbe.Native+StartupInfo +[RVBoxDesktopProbe.Native]::GetStartupInfoW([ref]$startup) +$state = [ordered]@{ + session_id = [Diagnostics.Process]::GetCurrentProcess().SessionId + user_sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value + window_station = [RVBoxDesktopProbe.Native]::Name([RVBoxDesktopProbe.Native]::GetProcessWindowStation()) + desktop = [RVBoxDesktopProbe.Native]::Name([RVBoxDesktopProbe.Native]::GetThreadDesktop([RVBoxDesktopProbe.Native]::GetCurrentThreadId())) + input_desktop = '' + input_desktop_error = 0 + window_observed = $false + has_console = ([RVBoxDesktopProbe.Native]::GetConsoleCP() -ne 0) + console_window_visible = [RVBoxDesktopProbe.Native]::IsWindowVisible([RVBoxDesktopProbe.Native]::GetConsoleWindow()) + startup_use_show_window = (($startup.flags -band 1) -ne 0) + startup_show_window = $startup.showWindow +} +$inputDesktop = [RVBoxDesktopProbe.Native]::OpenInputDesktop(0, $false, 1) +if ($inputDesktop -ne [IntPtr]::Zero) { + try { $state.input_desktop = [RVBoxDesktopProbe.Native]::Name($inputDesktop) } + finally { [void][RVBoxDesktopProbe.Native]::CloseDesktop($inputDesktop) } +} else { $state.input_desktop_error = [Runtime.InteropServices.Marshal]::GetLastWin32Error() } +$form = New-Object System.Windows.Forms.Form +$form.Text = 'RVBox interactive desktop test' +$form.Width = 540; $form.Height = 170 +$form.StartPosition = 'CenterScreen' +$label = New-Object System.Windows.Forms.Label +$label.AutoSize = $false; $label.Dock = 'Fill'; $label.TextAlign = 'MiddleCenter' +$label.Text = "RVBox launched this window on your desktop.`r`nIt closes automatically after $Seconds seconds." +$form.Controls.Add($label) +$form.Add_Shown({ + if ([RVBoxDesktopProbe.Native]::IsWindowVisible($form.Handle)) { $state.window_observed = $true } +}) +$timer = New-Object System.Windows.Forms.Timer +$timer.Interval = 100 +$elapsed = [Diagnostics.Stopwatch]::StartNew() +$timer.Add_Tick({ + if ([RVBoxDesktopProbe.Native]::IsWindowVisible($form.Handle)) { $state.window_observed = $true } + if ($elapsed.Elapsed.TotalSeconds -ge $Seconds) { $form.Close() } +}) +$timer.Start() +try { [System.Windows.Forms.Application]::Run($form) } +finally { $timer.Stop(); $timer.Dispose(); $form.Dispose() } +$state | ConvertTo-Json -Compress +if (-not $state.window_observed -or $state.session_id -eq 0 -or + $state.window_station -ine 'WinSta0' -or $state.desktop -ine 'Default' -or + $state.input_desktop -ine 'Default' -or $state.console_window_visible) { exit 2 } +exit 0 diff --git a/test/coverage.toml b/test/coverage.toml index 83aa30d..ee55e7a 100644 --- a/test/coverage.toml +++ b/test/coverage.toml @@ -1,5 +1,41 @@ version = 1 +[[requirements]] +id = "HP-DESKTOP-01" +layer = "unit" +status = "implemented" +tests = ["internal/client/supervisor/windows/desktop_test.go:TestDesktopPlacementFollowsSelectedIdentity_HP_DESKTOP_01"] + +[[requirements]] +id = "BH-DESKTOP-01" +layer = "unit" +status = "implemented" +tests = ["internal/client/supervisor/windows/desktop_test.go:TestDesktopRejectsWrongSessionAndSecureTargets_BH_DESKTOP_01"] + +[[requirements]] +id = "BH-DESKTOP-02" +layer = "unit" +status = "implemented" +tests = ["internal/client/supervisor/windows/desktop_test.go:TestDesktopFailureDiagnosticIsBounded_BH_DESKTOP_02"] + +[[requirements]] +id = "HP-DESKTOP-02" +layer = "integration" +status = "implemented" +tests = ["internal/client/supervisor/windows/desktop_windows_test.go:TestNativeDesktopAccessOnActualThread_HP_DESKTOP_02"] + +[[requirements]] +id = "HP-DESKTOP-03" +layer = "integration" +status = "implemented" +tests = ["internal/client/supervisor/windows/desktop_windows_test.go:TestNativeLauncherShowsGUIOnSelectedDesktop_HP_DESKTOP_03"] + +[[requirements]] +id = "HP-DESKTOP-04" +layer = "integration" +status = "implemented" +tests = ["internal/client/supervisor/windows/desktop_windows_test.go:TestNativeHeadlessConsoleStillReceivesTERM_HP_DESKTOP_04"] + [[requirements]] id = "BH-RUNTIME-09" layer = "unit"