From a37e7fed6fd4dc210ae6d2170112463d7956a1d3 Mon Sep 17 00:00:00 2001 From: Shroap <184123002+YinLiaoCo@users.noreply.github.com> Date: Fri, 4 Dec 2026 17:10:32 +0800 Subject: [PATCH] fix(guesttools,ui): handle macOS Network Volumes access for drops --- ...drop-mount-network-volumes-permission.json | 7 + frontend/scripts/test-guest-tools.mjs | 120 +++++++++++--- frontend/src/App.tsx | 30 +++- .../src/components/vmPage/connections.tsx | 10 ++ frontend/src/i18n/domains/vm.gen.ts | 4 + frontend/src/i18n/keys.gen.ts | 2 + frontend/src/styles/app.css | 2 + frontend/src/wails.ts | 2 + frontend/wailsjs/go/models.ts | 4 + internal/app/guesttools_flow.go | 1 + internal/app/stats_flow.go | 10 +- internal/app/stats_flow_test.go | 88 ++++++---- internal/guesttools/clipboard_agent_test.go | 91 ++++++++++- .../guesttools/clipboard_readability_test.go | 152 ++++++++++++++++-- internal/guesttools/control_loop_test.go | 73 +++++++++ internal/guesttools/drop_agent.sh | 62 ++++++- internal/guesttools/drop_agent_test.go | 142 +++++++++++----- internal/guesttools/drop_resolve.js | 108 +++++++------ internal/guesttools/drop_status_test.go | 58 +++++++ internal/guesttools/folder_share.go | 3 +- internal/guesttools/image.go | 43 ++++- internal/guesttools/server.go | 5 + internal/guesttools/testdata/pasteboard.cjs | 55 ++++++- internal/macos/reims/reims.go | 2 + locales/en-US/vm.json | 2 + locales/zh-CN/vm.json | 2 + 26 files changed, 896 insertions(+), 182 deletions(-) create mode 100644 changes/drop-mount-network-volumes-permission.json create mode 100644 internal/guesttools/drop_status_test.go diff --git a/changes/drop-mount-network-volumes-permission.json b/changes/drop-mount-network-volumes-permission.json new file mode 100644 index 0000000..3ffce83 --- /dev/null +++ b/changes/drop-mount-network-volumes-permission.json @@ -0,0 +1,7 @@ +{ + "group": "fixes", + "order": 0, + "authors": ["YinLiaoCo"], + "zh": "文件拖放通过 WebDAV 挂载导入文件,而 Guest Tools 后台以 `sh` 运行。修复全新 macOS 虚拟机首次拖放时未弹出 `sh`「网络宗卷」授权提示导致失败的问题;若权限被拒,拖放会立即提示「文件拖放受限」并在连接卡显示开启路径。开启权限后,拖入访达窗口或照片时会自动重挂仍无法获取文件引用的陈旧挂载;其他挂载故障及文件剪贴板仍保留下载兜底。已有虚拟机需将 Guest Tools 更新至 `v21`。", + "en": "File drops transfer files over a WebDAV mount read by the Guest Tools background agent (`sh`). macOS now prompts for `sh` Network Volumes access when needed during a drop. If access is denied, drops fail immediately with a File drop limited toast and a Connection card notice showing where to enable it. After access is granted, drops into Finder windows or Photos automatically remount stale WebDAV mounts whose file references are unavailable. Other mount failures and file clipboard sync keep download fallback. Update Guest Tools to `v21` in existing VMs." +} diff --git a/frontend/scripts/test-guest-tools.mjs b/frontend/scripts/test-guest-tools.mjs index 8909d11..0646160 100644 --- a/frontend/scripts/test-guest-tools.mjs +++ b/frontend/scripts/test-guest-tools.mjs @@ -1,36 +1,104 @@ import assert from 'node:assert/strict' -import test from 'node:test' +import test, { after, before } from 'node:test' import { loadTestModule } from './load-test-module.mjs' -test('Guest Tools offers an update when a connected guest is older than the bundled agent', async () => { +let fixture +before(async () => { // Wails reads its window bindings at import time. Static rendering uses the VM detail before the first live poll. globalThis.window = {} - try { - const { render } = await loadTestModule(` - import { createElement } from 'react' - import { renderToStaticMarkup } from 'react-dom/server.edge' - import { TooltipProvider } from './ui/controls' - import { VMPage } from './components/VMPage' + fixture = await loadTestModule(` + import { createElement } from 'react' + import { renderToStaticMarkup } from 'react-dom/server.edge' + import { TooltipProvider } from './ui/controls' + import { VMPage } from './components/VMPage' + import { ConnectionSection } from './components/vmPage/connections' + export { showHostDropAck } from './App' - export function render(installed, bundled, connected = true) { - return renderToStaticMarkup(createElement(TooltipProvider, null, createElement(VMPage, { - locale: 'en-US', name: 'mac', driverID: '', state: 'running', macosMajor: null, - host: {}, pending: [], currentAgentVersion: bundled, - detail: { guest_tools_configured: true, guest_tools_connected: connected, guest_tools_agent_version: installed } - }))) + export function render({ locale = 'en-US', installed = 21, bundled = 21, connected = true, denied, disabled = false } = {}) { + const detail = { + guest_tools_configured: true, + guest_tools_connected: connected, + guest_tools_agent_version: installed, + guest_tools_drop_access_denied: denied, + guest_tools_disabled: disabled, } - `) - for (const [guest, bundled, connected, needsUpdate] of [ - [13, 14, true, true], [14, 14, true, false], [14, 15, true, true], - [15, 15, true, false], [16, 15, true, false], [14, 15, false, false], - [15, 14, true, false], [0, 14, true, false], [13, 14, false, false], - ]) { - const html = render(guest, bundled, connected) - const context = `guest v${guest}, bundled v${bundled}, connected=${connected}` - assert.equal(html.includes('>Update needed<'), needsUpdate, context) - assert.equal(html.includes('Update…'), needsUpdate, context) + return renderToStaticMarkup(createElement(TooltipProvider, null, createElement(VMPage, { + locale, name: 'mac', driverID: '', state: 'running', macosMajor: null, + host: {}, pending: [], currentAgentVersion: bundled, detail, + }))) } - } finally { - delete globalThis.window + + export function renderLiveConnection(detailDenied, liveDenied) { + return renderToStaticMarkup(createElement(TooltipProvider, null, createElement(ConnectionSection, { + locale: 'en-US', vmKey: 'mac', state: 'running', pending: [], currentAgentVersion: 21, + detail: { ssh_port: 0, guest_tools_drop_access_denied: detailDenied }, + stats: { guest_tools_connected: true, guest_tools_drop_access_denied: liveDenied }, + }))) + } + `) +}) +after(() => { delete globalThis.window }) + +const permissionCopy = [ + ['en-US', 'File drop limited', 'File drops transfer via WebDAV. Enable Network Volumes for sh in macOS System Settings → Privacy & Security → Files and Folders'], + ['zh-CN', '文件拖放受限', '拖放通过 WebDAV 传输文件,请在 macOS「系统设置 → 隐私与安全性 → 文件与文件夹」中开启 sh 的「网络宗卷」权限'], +] + +test('Guest Tools offers an update when a connected guest is older than the bundled agent', () => { + for (const [installed, bundled, connected, needsUpdate] of [ + [13, 14, true, true], [14, 14, true, false], [14, 15, true, true], + [15, 15, true, false], [16, 15, true, false], [14, 15, false, false], + [15, 14, true, false], [0, 14, true, false], [13, 14, false, false], + ]) { + const html = fixture.render({ installed, bundled, connected }) + const context = `guest v${installed}, bundled v${bundled}, connected=${connected}` + assert.equal(html.includes('>Update needed<'), needsUpdate, context) + assert.equal(html.includes('Update…'), needsUpdate, context) } }) + +test('Guest Tools shows a localized idle sub-row only while connected and denied', () => { + for (const [locale, title, guidance] of permissionCopy) { + const html = fixture.render({ locale, denied: true }) + const subRow = '
' + + '' + + `${title}${guidance.replaceAll('&', '&')}
` + assert.ok(html.includes(subRow), locale) + + for (const [state, overrides] of [ + ['allowed', { denied: false }], + ['unprompted', { denied: undefined }], + ['disabled', { denied: true, disabled: true }], + ['disconnected', { denied: true, connected: false }], + ]) { + const hidden = fixture.render({ locale, ...overrides }) + assert.ok(!hidden.includes('conn-drop-access') && !hidden.includes(title), `${locale}, ${state}`) + } + } +}) + +test('Guest Tools shows the current drop permission even when detail is stale', () => { + assert.ok(fixture.renderLiveConnection(false, true).includes('conn-drop-access')) + assert.ok(!fixture.renderLiveConnection(true, false).includes('conn-drop-access')) +}) + +test('A failed Network Volumes drop shows the localized permission toast', () => { + for (const [locale, title, description] of permissionCopy) { + const toasts = [] + fixture.showHostDropAck({ status: 'failed', error: 'Network Volumes permission denied' }, locale, + (toast) => toasts.push(toast), () => assert.fail(`${locale} used the generic drop failure`)) + assert.deepEqual(toasts, [{ kind: 'error', title, description }], locale) + } +}) + +test('Other drop failures keep their details and successful or cancelled drops produce no error toast', () => { + const failures = [] + const push = () => assert.fail('unexpected permission toast') + const fail = (...args) => failures.push(args) + fixture.showHostDropAck({ status: 'failed', error: 'Placement failed' }, 'en-US', push, fail) + assert.deepEqual(failures, [['Couldn’t drop into the VM', 'Placement failed']]) + for (const status of ['placed', 'pasted', 'cancelled']) { + fixture.showHostDropAck({ status, error: 'Network Volumes permission denied' }, 'en-US', push, fail) + } + assert.equal(failures.length, 1) +}) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 403995e..7f39083 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -35,9 +35,9 @@ import { buildSafePluginAssetURL } from './lib/pluginAssets' import { ActiveThemePayload, AppState, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMAction, VMBusyAction, VMDetail, VMInfo, VMListItem, ViewContribution } from './types' import { Button, Tip, TooltipProvider } from './ui/controls' import { ConfirmDialog, Modal } from './ui/dialog' -import { errorToast, Toaster, useToasts } from './ui/toast' +import { errorToast, Toaster, type ToastInput, useToasts } from './ui/toast' import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals' -import { api, events, WindowMinimise, WindowToggleMaximise, type ElevationPrompt } from './wails' +import { api, DROP_NETWORK_VOLUMES_DENIED, events, WindowMinimise, WindowToggleMaximise, type ElevationPrompt } from './wails' // Opened on demand, so each is its own chunk and stays out of the startup // bundle: the wizard, VM settings and affinity dialogs, first-run setup, and @@ -56,6 +56,26 @@ const AboutPage = lazy(() => import('./components/AboutPage').then((m) => ({ def const errText = (e: unknown) => parseAppError(e).summary +type HostDropAck = { status: string; error?: string } + +export function showHostDropAck( + ack: HostDropAck, + locale: Locale, + pushToast: (toast: ToastInput) => void, + fail: (title: string, error: string) => void, +) { + if (ack.status !== 'failed') return + if (ack.error === DROP_NETWORK_VOLUMES_DENIED) { + pushToast({ + kind: 'error', + title: t(locale, 'gtDropAccessLimited'), + description: t(locale, 'gtDropAccessHint'), + }) + return + } + fail(t(locale, 'failDrop'), ack.error || '') +} + const failKey: Record = { start: 'failStart', suspend: 'failSuspend', @@ -146,7 +166,7 @@ export const App: React.FC = () => { logsOpenRef.current = logsOpen const [taskMap, setTaskMap] = useState>({}) const onTaskRef = useRef<(task: Task) => void>(() => {}) - const onHostDropAckRef = useRef<(ack: { status: string; error?: string }) => void>(() => {}) + const onHostDropAckRef = useRef<(ack: HostDropAck) => void>(() => {}) const notifiedTasks = useRef(new Map()) const [setupStage, setSetupStage] = useState<'folder' | 'runtime' | null>(null) @@ -639,9 +659,7 @@ export const App: React.FC = () => { }) } const update = useAppUpdate({ ready: !!state, tasks: taskMap, runningVMCount, onError: (e) => fail(tr('updateFailed'), e) }) - onHostDropAckRef.current = (ack) => { - if (ack.status === 'failed') fail(tr('failDrop'), ack.error || '') - } + onHostDropAckRef.current = (ack) => showHostDropAck(ack, locale, toasts.push, fail) const runVMAction = async (name: string, action: VMBusyAction, fn: () => Promise, okTitle?: string) => { const token = vmBusy.begin(name, action) diff --git a/frontend/src/components/vmPage/connections.tsx b/frontend/src/components/vmPage/connections.tsx index 8fb26f2..90a06ea 100644 --- a/frontend/src/components/vmPage/connections.tsx +++ b/frontend/src/components/vmPage/connections.tsx @@ -44,6 +44,7 @@ export const ConnectionSection: React.FC = ({ const tools = !installing if (!tools && detail.ssh_port <= 0) return null const gtConnected = stats?.guest_tools_connected ?? detail.guest_tools_connected ?? false + const gtDropAccessDenied = stats?.guest_tools_drop_access_denied ?? detail.guest_tools_drop_access_denied ?? false const gtMountMode = stats?.guest_tools_mount_mode || detail.guest_tools_mount_mode || '' const gtSleepActive = stats?.guest_tools_sleep_guard ?? detail.guest_tools_sleep_active ?? false const gtAgentVersion = stats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0 @@ -110,6 +111,15 @@ export const ConnectionSection: React.FC = ({ )} + {tools && gtConnected && !gtOff && gtDropAccessDenied && ( +
+ + + {tr('gtDropAccessHint')} +
+ )} {tools && showInstallCmd && (
diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index 34aef86..e4b185d 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -95,6 +95,8 @@ export const vmZh: Record = { "fieldVMName": "虚拟机名称", "finishInstall": "退出恢复模式", "gpuAuto": "自动选择 GPU", + "gtDropAccessHint": "拖放通过 WebDAV 传输文件,请在 macOS「系统设置 → 隐私与安全性 → 文件与文件夹」中开启 sh 的「网络宗卷」权限", + "gtDropAccessLimited": "文件拖放受限", "gtInstall": "安装…", "gtInstallSub": "在 macOS 终端里运行", "gtNotInstalledDesc": "未安装:挂载工具盘后在 macOS 中运行安装命令", @@ -351,6 +353,8 @@ export const vmEn: Record = { "fieldVMName": "VM name", "finishInstall": "Exit recovery mode", "gpuAuto": "Automatic GPU", + "gtDropAccessHint": "File drops transfer via WebDAV. Enable Network Volumes for sh in macOS System Settings → Privacy \u0026 Security → Files and Folders", + "gtDropAccessLimited": "File drop limited", "gtInstall": "Install…", "gtInstallSub": "Run in macOS Terminal", "gtNotInstalledDesc": "Not installed: attach the tools disk and run the installer in macOS", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 3e34e97..57e3cbd 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -405,6 +405,8 @@ export type I18nKey = | "groupMacOS" | "groupPerformance" | "groupQemu" + | "gtDropAccessHint" + | "gtDropAccessLimited" | "gtInstall" | "gtInstallSub" | "gtNotInstalledDesc" diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 1ddac6b..bc4a002 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -459,6 +459,8 @@ h1, h2, h3, p { margin: 0; } .conn-row.conn-sub { min-height: 40px; padding-top: 0; padding-left: 28px; } .conn-row.conn-sub::before { display: none; } .conn-row.conn-sub .conn-main { flex: 0 0 auto; } +.conn-row.conn-drop-access { justify-content: flex-start; } +.conn-drop-access .conn-meta { white-space: normal; } .conn-ctrl { display: flex; align-items: center; gap: 6px; flex-shrink: 0; } .conn-ctrl-grow { flex: 1; flex-shrink: 1; min-width: 0; justify-content: flex-end; } .conn-ctrl .btn { height: 28px; padding: 0 11px; font-size: 12.5px; } diff --git a/frontend/src/wails.ts b/frontend/src/wails.ts index a58d88d..8d9915d 100644 --- a/frontend/src/wails.ts +++ b/frontend/src/wails.ts @@ -192,6 +192,8 @@ export interface ElevationPrompt { needs_logoff?: boolean } +export const DROP_NETWORK_VOLUMES_DENIED = 'Network Volumes permission denied' + export const events = { onHostDrop: (cb: (payload: { vm: string; drop_id: string; delivered: string[]; skipped?: string[]; mode: string }) => void) => eventsOn('reims:host-drop', cb), onHostDropAck: (cb: (payload: { vm: string; drop_id: string; status: string; target_kind?: string; target_label?: string; placed_names?: string[]; error?: string }) => void) => eventsOn('reims:host-drop-ack', cb), diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 8b1880d..80f60be 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -715,6 +715,7 @@ export namespace app { uptime_seconds: number; guest_tools_connected: boolean; guest_tools_mount_mode?: string; + guest_tools_drop_access_denied: boolean; guest_tools_agent_version?: number; guest_tools_sleep_guard: boolean; @@ -742,6 +743,7 @@ export namespace app { this.uptime_seconds = source["uptime_seconds"]; this.guest_tools_connected = source["guest_tools_connected"]; this.guest_tools_mount_mode = source["guest_tools_mount_mode"]; + this.guest_tools_drop_access_denied = source["guest_tools_drop_access_denied"]; this.guest_tools_agent_version = source["guest_tools_agent_version"]; this.guest_tools_sleep_guard = source["guest_tools_sleep_guard"]; } @@ -3137,6 +3139,7 @@ export namespace reims { guest_tools_prevent_sleep: boolean; guest_tools_sleep_active: boolean; guest_tools_agent_version?: number; + guest_tools_drop_access_denied: boolean; guest_tools_disabled?: boolean; shared_dir?: string; guest_lang?: string; @@ -3188,6 +3191,7 @@ export namespace reims { this.guest_tools_prevent_sleep = source["guest_tools_prevent_sleep"]; this.guest_tools_sleep_active = source["guest_tools_sleep_active"]; this.guest_tools_agent_version = source["guest_tools_agent_version"]; + this.guest_tools_drop_access_denied = source["guest_tools_drop_access_denied"]; this.guest_tools_disabled = source["guest_tools_disabled"]; this.shared_dir = source["shared_dir"]; this.guest_lang = source["guest_lang"]; diff --git a/internal/app/guesttools_flow.go b/internal/app/guesttools_flow.go index 36869bb..88bcaba 100644 --- a/internal/app/guesttools_flow.go +++ b/internal/app/guesttools_flow.go @@ -380,6 +380,7 @@ func (a *App) populateGuestToolsDetail(d *reims.VMDetail, epoch uint64) { st := srv.Status(d.Name, 15*time.Second) d.GuestToolsConnected = st.Connected d.GuestToolsMountMode = st.MountMode + d.GuestToolsDropAccessDenied = st.DropMountDenied d.GuestToolsSleepActive = st.SleepActive d.GuestToolsAgentVersion = st.AgentVersion } diff --git a/internal/app/stats_flow.go b/internal/app/stats_flow.go index 24c78fd..2e5d9d8 100644 --- a/internal/app/stats_flow.go +++ b/internal/app/stats_flow.go @@ -27,10 +27,11 @@ type VMStats struct { DiskBackingDepthWarn bool `json:"disk_backing_depth_warn,omitempty"` UptimeSeconds int64 `json:"uptime_seconds"` - GuestToolsConnected bool `json:"guest_tools_connected"` - GuestToolsMountMode string `json:"guest_tools_mount_mode,omitempty"` - GuestToolsAgentVersion int `json:"guest_tools_agent_version,omitempty"` - GuestToolsSleepGuard bool `json:"guest_tools_sleep_guard"` + GuestToolsConnected bool `json:"guest_tools_connected"` + GuestToolsMountMode string `json:"guest_tools_mount_mode,omitempty"` + GuestToolsDropAccessDenied bool `json:"guest_tools_drop_access_denied"` + GuestToolsAgentVersion int `json:"guest_tools_agent_version,omitempty"` + GuestToolsSleepGuard bool `json:"guest_tools_sleep_guard"` } // GetVMStats samples host-side process and disk telemetry through the owning driver. @@ -104,6 +105,7 @@ func (a *App) GetVMStats(driverID, name string) (VMStats, error) { st := srv.Status(vm.Name, 15*time.Second) stats.GuestToolsConnected = st.Connected stats.GuestToolsMountMode = st.MountMode + stats.GuestToolsDropAccessDenied = st.DropMountDenied stats.GuestToolsAgentVersion = st.AgentVersion stats.GuestToolsSleepGuard = st.SleepActive } diff --git a/internal/app/stats_flow_test.go b/internal/app/stats_flow_test.go index d52aaa8..c8c3209 100644 --- a/internal/app/stats_flow_test.go +++ b/internal/app/stats_flow_test.go @@ -16,20 +16,24 @@ import ( "github.com/Nwflower/reims-go/internal/plugin" ) -func TestVMStatsReportsLiveGuestToolsAgentVersion(t *testing.T) { +func TestVMStatsAndDetailReportLiveGuestToolsStatus(t *testing.T) { cfg := &config.Config{DataRoot: t.TempDir()} + vm := folderTestVM(t, cfg.DataRoot) srv := guesttools.NewTransportServer(nil) port, err := srv.Start(-1) if err != nil { t.Fatal(err) } t.Cleanup(func() { srv.Close(context.Background()) }) - const name = "mac" - const token = "test-token" - srv.RegisterVM(guesttools.VMConfig{VMName: name, Token: token}) + token := strings.Repeat("a", 64) + guestCfg := guesttools.VMConfig{VMName: vm.Name, Token: token, Port: port} + if err := guesttools.SaveVMConfig(vm.Directory, guestCfg); err != nil { + t.Fatal(err) + } + srv.RegisterVM(guestCfg) drv := &appSecondDriver{ id: driver.BuiltinReimsMacOSDriverID, - vms: []driver.VMInfo{{Name: name, DriverID: driver.BuiltinReimsMacOSDriverID, Directory: cfg.DataRoot, State: "running"}}, + vms: []driver.VMInfo{{Name: vm.Name, DriverID: driver.BuiltinReimsMacOSDriverID, Directory: vm.Directory, State: "running"}}, } reg := plugin.NewRegistry(nil) if err := reg.Register(plugin.PluginDef{ @@ -47,28 +51,56 @@ func TestVMStatsReportsLiveGuestToolsAgentVersion(t *testing.T) { router := driver.NewRouter(reg, nil) now := time.Now() a := &App{cfg: cfg, guestTools: srv, lastVMsAt: now, lifecycleSvc: vmlifecycle.New(reg, router, nil)} - for _, version := range []int{6, 7} { - payload := fmt.Sprintf(`{"mount_mode":"webdav","agent_version":%d}`, version) - req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/v1/status", port), strings.NewReader(payload)) - if err != nil { - t.Fatal(err) - } - req.Header.Set("Authorization", "Bearer "+token) - res, err := http.DefaultClient.Do(req) - if err != nil { - t.Fatal(err) - } - res.Body.Close() - if res.StatusCode != http.StatusOK { - t.Fatalf("agent status: %s", res.Status) - } - stats, err := a.GetVMStats("", name) - if err != nil || !stats.GuestToolsConnected || stats.GuestToolsAgentVersion != version { - t.Fatalf("VM stats: %+v, %v", stats, err) - } - encoded, err := json.Marshal(stats) - if err != nil || !strings.Contains(string(encoded), fmt.Sprintf(`"guest_tools_agent_version":%d`, version)) { - t.Fatalf("VM stats JSON: %s, %v", encoded, err) - } + for _, tc := range []struct { + name string + field string + version int + denied bool + }{ + {"denied", `,"drop_mount_denied":true`, guesttools.DropNetworkVolumesAgentVersion, true}, + {"allowed_again", `,"drop_mount_denied":false`, guesttools.DropNetworkVolumesAgentVersion, false}, + {"denied_again", `,"drop_mount_denied":true`, guesttools.DropNetworkVolumesAgentVersion, true}, + {"older_agent", "", guesttools.SharedFolderWebDAVAgentVersion, false}, + } { + t.Run(tc.name, func(t *testing.T) { + payload := fmt.Sprintf(`{"mount_mode":"webdav","agent_version":%d%s}`, tc.version, tc.field) + req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/v1/status", port), strings.NewReader(payload)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+token) + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + res.Body.Close() + if res.StatusCode != http.StatusOK { + t.Fatalf("agent status: %s", res.Status) + } + stats, err := a.GetVMStats("", vm.Name) + if err != nil || !stats.GuestToolsConnected || stats.GuestToolsAgentVersion != tc.version || stats.GuestToolsDropAccessDenied != tc.denied { + t.Fatalf("VM stats: %+v, %v", stats, err) + } + detail, err := a.GetVMDetail(vm.Name) + if err != nil || !detail.GuestToolsConnected || detail.GuestToolsAgentVersion != tc.version || detail.GuestToolsDropAccessDenied != tc.denied { + t.Fatalf("VM detail: %+v, %v", detail, err) + } + for _, value := range []any{stats, detail} { + encoded, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + var wire struct { + Version int `json:"guest_tools_agent_version"` + Denied *bool `json:"guest_tools_drop_access_denied"` + } + if err := json.Unmarshal(encoded, &wire); err != nil { + t.Fatal(err) + } + if wire.Version != tc.version || wire.Denied == nil || *wire.Denied != tc.denied { + t.Fatalf("%T JSON must include version %d and explicit denial %t: %s", value, tc.version, tc.denied, encoded) + } + } + }) } } diff --git a/internal/guesttools/clipboard_agent_test.go b/internal/guesttools/clipboard_agent_test.go index 0601183..ada3ac8 100644 --- a/internal/guesttools/clipboard_agent_test.go +++ b/internal/guesttools/clipboard_agent_test.go @@ -38,6 +38,7 @@ func TestGuestAgentClipboardScript(t *testing.T) { t.Fatal("POST must guard empty positional arguments under Bash 3.2 set -u") } textInput := scriptSection(t, agent, "inject_text() {", "\ntext_input_loop &") + dropProbe := scriptSection(t, guestDropAgent, "\ndrop_helper() {", "\nplace_drop_unique() (") hashing := scriptSection(t, agent, "hash_file() {", "update_desktop_link() {") _, mainLoop, _ := strings.Cut(agent, "\ntext_input_loop &") @@ -116,6 +117,10 @@ func TestGuestAgentClipboardScript(t *testing.T) { "host_files_receipt", "host_files_both_receipts", "host_files_unreadable_fallback", "host_files_unreadable_fallback_conflict", "host_files_unreadable_without_fallback", "host_files_no_ack_failed_write", }}, + {"file_permissions", []string{ + "host_files_permission_allow", "host_files_permission_deny", "host_files_permission_cached_deny", + "host_files_permission_changed_during_probe", + }}, {"file_upload", []string{"guest_files_tar_upload", "guest_files_legacy_no_upload", "guest_files_tar_hosted_no_upload", "guest_files_tar_upload_changed", "guest_files_tar_upload_retry"}}, {"file_retry", []string{ "host_files_remount_and_fail_no_spin", "host_files_new_event_during_retry", @@ -134,7 +139,7 @@ func TestGuestAgentClipboardScript(t *testing.T) { tmp := t.TempDir() script := filepath.Join(tmp, "clipboard-test.sh") code := "set -eu\nPATH=\"/usr/bin:/bin:$PATH\"\nnow=$(date +%s)\nrun_case() (\ncd \"$1\"\n" + - agent[start:end] + textInput + clipboardShellFixture + agent[start:end] + textInput + dropProbe + clipboardShellFixture if group.name == "worker" { code += "\nif [ \"$1\" = clipboard_worker ]; then\ntext_input_loop &" + mainLoop + "\nfi\n" } @@ -145,7 +150,7 @@ func TestGuestAgentClipboardScript(t *testing.T) { } } var cmdEnv []string - if group.name == "file_delivery" || group.name == "file_readiness" { + if group.name == "file_delivery" || group.name == "file_readiness" || group.name == "file_permissions" { fixture, err := filepath.Abs("testdata/pasteboard.cjs") if err != nil { t.Fatal(err) @@ -230,6 +235,7 @@ printf A > local_value : > clip_work local_info="Unicode text" flags="" +permission_choice="" failure_kind="" fail_during_get=0 get_code=200 @@ -282,6 +288,10 @@ ensure_drop_webdav_mount() { if [ ! -s mount_owner ]; then printf owned > mount_owner; fi } unmount_shared_folder() { echo unmount >> mounts; : > mount_owner; } +drop_mount_readable() { + printf 'check\n' >> permission_checks + return 2 +} pbpaste() { case "$flags" in inject_read) : > "$INJECT_LOCK" ;; @@ -336,6 +346,10 @@ osascript() { write-clip-files) { [ "$6" = "$DROP_MOUNT" ] || [ "$6/${8:-}" = "$CLIP_CACHE/cache" ]; } && [ "$(read_file "$5")" = "$get_value" ] || return 1 + if [ -n "$permission_choice" ]; then + [ -d "$CLIP_LOCK" ] || exit 1 + printf '%s %s\n' "$6" "$7" >> permission_writes + fi echo write >> writes if [ "$flags" = typed_files ]; then node "$PASTEBOARD_FIXTURE" "$3" write-clip-files "$5" "$6" "$7" "${8:-}" || return 1 @@ -349,6 +363,22 @@ osascript() { echo ok fi ;; + probe-mount) + [ ! -d "$CLIP_LOCK" ] || exit 1 + expect "$#/$5" "5/$DROP_MOUNT" + printf '%s\n' "$permission_choice" >> permission_prompts + case "$permission_choice" in + deny) printf 'denied\n' ;; + allow|allow_changed) + printf '{}\n' > test-hosted-probe-errors.json + if [ "$permission_choice" = allow_changed ]; then + printf '%s\n' '{"changeCount":2,"items":[{"public.utf8-plain-text":"new guest copy"}]}' > test-pasteboard.json + fi + printf 'ok\n' + ;; + *) return 1 ;; + esac + ;; clip-manifest-id|validate-clip-archive) node "$PASTEBOARD_FIXTURE" "$3" "$4" "$5" "${6:-}" ;; local-clip-paths) @@ -708,6 +738,63 @@ a%23note.txt' ;; esac ;; + host_files_permission_*) + flags=typed_files + get_kind=files + get_hash=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + get_receipt=ABCDEFGHIJKLMNOPQRSTUVWXYZ + get_value='{"drop_id":"clip-0123456789abcdef","items":["fallback.txt"]}' + mkdir -p "$DROP_MOUNT/clip-0123456789abcdef" + printf mounted > "$DROP_MOUNT/clip-0123456789abcdef/fallback.txt" + printf '%s\n' '{"changeCount":1,"items":[{"public.utf8-plain-text":"A"}]}' > test-pasteboard.json + printf '%s\n' '{"./drop_mount/clip-0123456789abcdef/fallback.txt":"EPERM"}' > test-hosted-probe-errors.json + printf '0 1048576\n' > clip_file_config + printf downloaded > fallback.txt + tar -cf guest-fallback.tar fallback.txt + + case "$1" in + host_files_permission_allow) permission_choice=allow ;; + host_files_permission_changed_during_probe) permission_choice=allow_changed ;; + host_files_permission_deny) permission_choice=deny ;; + host_files_permission_cached_deny) + permission_choice=deny + : > "$TMP_DIR/drop_mount_denied" + ;; + esac + sync_clipboard + [ ! -e mounts ] && [ ! -d "$CLIP_LOCK" ] || exit 1 + if [ "$1" = host_files_permission_cached_deny ]; then + [ ! -e permission_prompts ] + expect "$(cat permission_checks)" check + else + expect "$(cat permission_prompts)" "$permission_choice" + [ ! -e permission_checks ] + fi + case "$permission_choice" in + allow) + [ ! -e "$TMP_DIR/drop_mount_denied" ] && [ ! -e "$CLIP_CACHE" ] || exit 1 + expect "$(cat permission_writes)" "$(printf '%s 1\n%s 1\n' "$DROP_MOUNT" "$DROP_MOUNT")" + expect "$(methods)" GET,FILE-ACK + expect "$(read_local_clipboard readback)" files + grep -q '/drop_mount/clip-0123456789abcdef/fallback.txt$' readback + ;; + allow_changed) + [ ! -e "$TMP_DIR/drop_mount_denied" ] && [ ! -e "$CLIP_CACHE" ] || exit 1 + expect "$(cat permission_writes)" "$(printf '%s 1\n%s 1\n' "$DROP_MOUNT" "$DROP_MOUNT")" + expect "$(methods)" GET + expect "$last_server_hash/$file_retry_polls" /3 + expect "$(node -p 'require("./test-pasteboard.json").items[0]["public.utf8-plain-text"]')" 'new guest copy' + ;; + deny) + [ -f "$TMP_DIR/drop_mount_denied" ] + expect "$(cat permission_writes)" "$(printf '%s 1\n%s 1\n' "$DROP_MOUNT" "$CLIP_CACHE")" + expect "$(methods)" GET,DOWNLOAD,FILE-ACK + expect "$(cat "$CLIP_CACHE/clip-0123456789abcdef/fallback.txt")" downloaded + expect "$(read_local_clipboard readback)" files + grep -q '/clip_cache/clip-0123456789abcdef/fallback.txt$' readback + ;; + esac + ;; host_files_tar_fallback|host_files_tar_fallback_changed) flags=typed_files get_kind=files diff --git a/internal/guesttools/clipboard_readability_test.go b/internal/guesttools/clipboard_readability_test.go index e703e8b..7f4121f 100644 --- a/internal/guesttools/clipboard_readability_test.go +++ b/internal/guesttools/clipboard_readability_test.go @@ -13,6 +13,111 @@ import ( "testing" ) +func TestGuestAgentProbesDropMountAccess(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("Node.js is unavailable") + } + fixture, err := filepath.Abs("testdata/pasteboard.cjs") + if err != nil { + t.Fatal(err) + } + const mount, scope = "mount", "mount/selection" + const referencePaths = mount + "\n" + scope + "\n" + type nativeError struct { + Domain string `json:"domain"` + Code int `json:"code"` + Underlying *nativeError `json:"underlying,omitempty"` + } + withPOSIX := func(code int) *nativeError { + return &nativeError{"NSCocoaErrorDomain", 256, &nativeError{Domain: "NSPOSIXErrorDomain", Code: code}} + } + for _, tc := range []struct { + name string + errorAt string + nativeError *nativeError + missingScope bool + missingRef string + perlErrno string + requireRef bool + want string + wantReferences string + }{ + {name: "readable root and scope", want: "ok"}, + {name: "desktop accepts a readable scope with a nil file reference", missingRef: scope, want: "ok"}, + {name: "non-desktop accepts readable paths with valid file references", requireRef: true, want: "ok", wantReferences: referencePaths}, + {name: "non-desktop rejects a readable scope with a nil file reference", missingRef: scope, requireRef: true, want: "unhealthy", wantReferences: referencePaths}, + {name: "non-desktop handles EPERM at scope before checking any file reference", errorAt: scope, nativeError: withPOSIX(1), missingRef: mount, requireRef: true, want: "denied"}, + {name: "Cocoa permission denial at root", errorAt: mount, nativeError: &nativeError{Domain: "NSCocoaErrorDomain", Code: 257}, want: "denied"}, + {name: "underlying POSIX EPERM at scope", errorAt: scope, nativeError: withPOSIX(1), want: "denied"}, + {name: "underlying POSIX EACCES at root", errorAt: mount, nativeError: withPOSIX(13), want: "denied"}, + {name: "missing drop scope", missingScope: true, want: "unhealthy"}, + {name: "underlying POSIX EIO", errorAt: scope, nativeError: withPOSIX(5), want: "unhealthy"}, + {name: "errno fallback without a bridged NSError", errorAt: mount, perlErrno: "EPERM", want: "denied"}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + write := func(name string, contents []byte) { + t.Helper() + if err := os.WriteFile(filepath.Join(dir, name), contents, 0o600); err != nil { + t.Fatal(err) + } + } + path := scope + if tc.missingScope { + path = mount + } + if err := os.MkdirAll(filepath.Join(dir, path), 0o700); err != nil { + t.Fatal(err) + } + write("drop-resolve.js", []byte(guestDropResolveJS)) + if tc.errorAt != "" { + data, err := json.Marshal(map[string]*nativeError{tc.errorAt: tc.nativeError}) + if err != nil { + t.Fatal(err) + } + write("test-mount-directory-errors.json", data) + } + if tc.perlErrno != "" { + data, err := json.Marshal(map[string]string{tc.errorAt: tc.perlErrno}) + if err != nil { + t.Fatal(err) + } + write("test-hosted-probe-errors.json", data) + } + if tc.missingRef != "" { + write("test-missing-file-reference", []byte(tc.missingRef)) + } + mode := "probe-mount" + if tc.requireRef { + mode = "probe-mount-ref" + } + cmd := exec.CommandContext(t.Context(), node, fixture, "drop-resolve.js", mode, mount, scope) + cmd.Dir = dir + output, err := cmd.CombinedOutput() + if got := strings.TrimSpace(string(output)); err != nil || got != tc.want { + t.Fatalf("probe mount = %q, want %q, err=%v", got, tc.want, err) + } + wantProbe := mount + "\t$()\n" + if tc.errorAt != mount { + wantProbe += scope + "\t$()\n" + } + probe, err := os.ReadFile(filepath.Join(dir, "test-mount-directory-probe.log")) + if err != nil || string(probe) != wantProbe { + t.Fatalf("Foundation calls = %q, want %q, err=%v", probe, wantProbe, err) + } + references, err := os.ReadFile(filepath.Join(dir, "test-mount-reference-probe.log")) + if tc.wantReferences == "" { + if !errors.Is(err, os.ErrNotExist) { + t.Fatalf("unexpected file reference calls = %q, err=%v", references, err) + } + } else if err != nil || string(references) != tc.wantReferences { + t.Fatalf("file reference calls = %q, want %q, err=%v", references, tc.wantReferences, err) + } + }) + } +} + func TestGuestAgentChecksHostedClipboardReadabilityBeforePublishing(t *testing.T) { node, err := exec.LookPath("node") if err != nil { @@ -26,16 +131,21 @@ func TestGuestAgentChecksHostedClipboardReadabilityBeforePublishing(t *testing.T const previous = `{"changeCount":7,"items":[{"public.utf8-plain-text":"guest copy"}]}` paths := []string{"mount/" + dropID + "/empty.txt", "mount/" + dropID + "/empty-dir", "mount/" + dropID + "/folder"} for _, tc := range []struct { - name string - denied string - mode string - want string - probe bool + name string + denied string + errno string + mode string + want string + probe bool + missingScope bool }{ {name: "files and folders readable", want: "ok", probe: true}, {name: "file stat passes but cannot read", denied: paths[0], want: "unreadable", probe: true}, {name: "directory stat passes but cannot list", denied: paths[1], want: "unreadable", probe: true}, - {name: "missing selection", want: "remount"}, + {name: "file open returns EPERM", denied: paths[0], errno: "EPERM", want: "denied", probe: true}, + {name: "directory read returns EACCES", denied: paths[1], errno: "EACCES", want: "denied", probe: true}, + {name: "missing scope with inaccessible mount", denied: "mount", errno: "EPERM", want: "denied", probe: true, missingScope: true}, + {name: "missing selection", want: "remount", probe: true}, {name: "local archive cache skips the network probe", denied: paths[0], mode: "cache", want: "ok"}, } { t.Run(tc.name, func(t *testing.T) { @@ -46,19 +156,32 @@ func TestGuestAgentChecksHostedClipboardReadabilityBeforePublishing(t *testing.T t.Fatal(err) } } - for _, path := range paths[1:] { + probePaths, dirs := paths, paths[1:] + if tc.missingScope { + probePaths = []string{"mount"} + dirs = probePaths + } + for _, path := range dirs { if err := os.MkdirAll(filepath.Join(dir, path), 0o700); err != nil { t.Fatal(err) } } - if tc.want != "remount" { - write(paths[0], "") + if !tc.missingScope { + if tc.want != "remount" { + write(paths[0], "") + } + write(paths[2]+"/first.txt", "first") } - write(paths[2]+"/first.txt", "first") write("manifest.json", `{"drop_id":"`+dropID+`","items":["empty.txt","empty-dir","folder"]}`) write("drop-resolve.js", guestDropResolveJS) write("test-pasteboard.json", previous) - if tc.denied != "" { + if tc.errno != "" { + data, err := json.Marshal(map[string]string{tc.denied: tc.errno}) + if err != nil { + t.Fatal(err) + } + write("test-hosted-probe-errors.json", string(data)) + } else if tc.denied != "" { data, err := json.Marshal([]string{tc.denied}) if err != nil { t.Fatal(err) @@ -75,12 +198,15 @@ func TestGuestAgentChecksHostedClipboardReadabilityBeforePublishing(t *testing.T probed, err := os.ReadFile(filepath.Join(dir, "test-hosted-probe.json")) if tc.probe { var got []string - if err != nil || json.Unmarshal(probed, &got) != nil || !slices.Equal(got, paths) { - t.Fatalf("probe paths = %q, want %v, err=%v", probed, paths, err) + if err != nil || json.Unmarshal(probed, &got) != nil || !slices.Equal(got, probePaths) { + t.Fatalf("probe paths = %q, want %v, err=%v", probed, probePaths, err) } } else if !errors.Is(err, os.ErrNotExist) { t.Fatalf("unexpected probe for %s, err=%v", tc.want, err) } + if _, err := os.Stat(filepath.Join(dir, "test-mount-directory-probe.log")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("clipboard write invoked the prompting probe, err=%v", err) + } if tc.want != "ok" { got, err := os.ReadFile(filepath.Join(dir, "test-pasteboard.json")) if err != nil || string(got) != previous { diff --git a/internal/guesttools/control_loop_test.go b/internal/guesttools/control_loop_test.go index fa595b9..deabebb 100644 --- a/internal/guesttools/control_loop_test.go +++ b/internal/guesttools/control_loop_test.go @@ -45,6 +45,79 @@ if command kill -0 "$worker_pid" 2>/dev/null; then fail "worker survived cleanup }) } +func TestGuestAgentDropMountHeartbeat(t *testing.T) { + agent := string(GuestAgentScript()) + report := scriptSection(t, agent, "\nreport_status() {", "\nread_local_clipboard() {") + dropProbe := scriptSection(t, guestDropAgent, "\ndrop_helper() {", "\nplace_drop_unique() (") + loop := scriptSection(t, agent, "\nwhile :; do\n reap_file_sync\n", "\ndone") + "done\n" + runShareShell(t, dropProbe+report+` +set -eu +TMP_DIR=. +REIMS_HOST_URL=http://stub +REIMS_TOKEN=token +REIMS_VM=guest +DROP_MOUNT=./drop_mount +mount_mode=webdav +keymap_active=false +sleep_active=false +timezone_helper_ready=false +timezone_error= +mounted=1 +mount_access=2 +tick=0 +load_conf() { :; } +apply_host_config() { :; } +ensure_webdav_mount() { :; } +ensure_drop_webdav_mount() { :; } +reap_file_sync() { :; } +current_timezone() { printf 'UTC\n'; } +urlencode() { printf '%s' "$1"; } +is_reims_dav_mounted() { + [ "$1" = "$DROP_MOUNT" ] && [ "$2" = /dav-drop/guest/ ] && [ "$mounted" = 1 ] +} +drop_mount_readable() { + printf '%s\n' "$tick" >> checks + return "$mount_access" +} +osascript() { printf '%s\n' "$*" >> prompts; return 1; } +curl() { + while [ "$1" != -d ]; do shift; done + [ "$3" = "$REIMS_HOST_URL/v1/status" ] || exit 1 + case "$2" in + *'"drop_mount_denied":false'*) printf '%s false\n' "$tick" >> status ;; + *'"drop_mount_denied":true'*) printf '%s true\n' "$tick" >> status ;; + *) exit 1 ;; + esac +} +sleep() { + [ ! -e prompts ] || { cat prompts >&2; exit 1; } + case "$tick" in + 1) + [ "$(cat status)" = '0 false' ] && [ ! -e checks ] || exit 1 + : > "$TMP_DIR/drop_mount_denied" + ;; + 2) + [ "$(cat status)" = "$(printf '0 false\n1 true')" ] || exit 1 + [ "$(cat checks)" = 1 ] && [ -f "$TMP_DIR/drop_mount_denied" ] || exit 1 + mounted=0 + ;; + 6) + [ "$(cat status)" = "$(printf '0 false\n1 true\n5 true')" ] || exit 1 + [ "$(cat checks)" = 1 ] && [ -f "$TMP_DIR/drop_mount_denied" ] || exit 1 + mounted=1 + mount_access=0 + ;; + 11) + cat status checks + [ "$(cat status)" = "$(printf '0 false\n1 true\n5 true\n10 false')" ] || exit 1 + [ "$(cat checks)" = "$(printf '1\n10')" ] && [ ! -e "$TMP_DIR/drop_mount_denied" ] || exit 1 + exit 0 + ;; + esac +} +`+loop, nil) +} + const fileSyncControlSetup = `set -eu TMP_DIR=. INJECT_LOCK=./injecting diff --git a/internal/guesttools/drop_agent.sh b/internal/guesttools/drop_agent.sh index 4bb2634..8c1721f 100644 --- a/internal/guesttools/drop_agent.sh +++ b/internal/guesttools/drop_agent.sh @@ -3,6 +3,43 @@ drop_helper() { osascript -l JavaScript "$APP_DIR/drop-resolve.js" "$@" } +drop_webdav_mounted() { + [ -n "${DROP_MOUNT:-}" ] && [ -n "${REIMS_VM:-}" ] && + is_reims_dav_mounted "$DROP_MOUNT" "/dav-drop/$(urlencode "$REIMS_VM")/" +} + +# Perl cannot prompt for Network Volumes. Use it for heartbeat checks and cached denials. +drop_mount_readable() { + /usr/bin/perl -MErrno=EPERM,EACCES -e ' + alarm 2; + sub failed { exit(($! == EPERM || $! == EACCES) ? 2 : 1) } + opendir(my $dir, $ARGV[0]) or failed(); + $! = 0; + defined(readdir($dir)) || !$! or failed(); + ' -- "$DROP_MOUNT" >/dev/null 2>&1 +} + +probe_drop_mount() ( + probe_mode=${1:-probe-mount} + if [ "$#" -gt 0 ]; then shift; fi + marker="$TMP_DIR/drop_mount_denied" + if [ -f "$marker" ]; then + access=0 + drop_mount_readable || access=$? + case "$access" in + 0) rm -f "$marker" ;; + 2) printf '%s\n' denied; return 0 ;; + esac + fi + access=$(drop_helper "$probe_mode" "$DROP_MOUNT" "$@" 2>/dev/null) || access=unhealthy + case "$access" in + ok) rm -f "$marker" ;; + denied) (umask 077; : > "$marker") ;; + *) access=unhealthy ;; + esac + printf '%s\n' "$access" +) + place_drop_unique() ( target_dir=$1 base=$2 part_file=$3 stem=$base ext= @@ -83,7 +120,7 @@ process_drop_event() ( trap 'exit 1' HUP INT TERM touch "$lock" || return 1 held=true - fast=$(REIMS_TOKEN="$REIMS_TOKEN" drop_helper run-drop "$1" "${DROP_MOUNT:-}" "$REIMS_HOST_URL/v1/drop-events/paste") || return 1 + fast=$(REIMS_TOKEN="$REIMS_TOKEN" drop_helper run-drop "$1" "$REIMS_HOST_URL/v1/drop-events/paste") || return 1 rm -f "$lock" || return 1 held=false exec 3</dev/null 2>&1; then ensure_drop_webdav_mount || :; fi - if [ -d "$DROP_MOUNT/$drop_id" ] && { [ "$t_kind" = desktop ] || - drop_helper check-mount "$DROP_MOUNT" "$DROP_MOUNT/$drop_id" >/dev/null 2>&1; }; then - mount_dir="$DROP_MOUNT/$drop_id" - break + if ! drop_webdav_mounted; then + ensure_drop_webdav_mount && drop_webdav_mounted || break fi - [ "$attempt" = first ] && command -v unmount_shared_folder >/dev/null 2>&1 && + case "$(probe_drop_mount "$probe_mode" "$DROP_MOUNT/$drop_id")" in + ok) mount_dir="$DROP_MOUNT/$drop_id"; break ;; + denied) + ack=$(drop_helper encode-ack "$drop_id" failed "$t_kind" "$label" 'Network Volumes permission denied') || return 1 + post_drop_ack "$ack" + return $? ;; + esac + [ "$attempt" = first ] && drop_webdav_mounted && unmount_shared_folder "$DROP_MOUNT" >/dev/null 2>&1 || break done fi @@ -202,7 +245,10 @@ EOF set -- ;; esac fi - if [ -n "$error" ]; then status=failed; if [ "$t_kind" != desktop ]; then set --; fi; fi + if [ -n "$error" ]; then + status=failed + if [ "$t_kind" != desktop ]; then set --; fi + fi if [ "$status" = cancelled ]; then t_kind=cancelled; label=; fi ack=$(drop_helper encode-ack "$drop_id" "$status" "$t_kind" "$label" "$error" "$@") || return 1 post_drop_ack "$ack" diff --git a/internal/guesttools/drop_agent_test.go b/internal/guesttools/drop_agent_test.go index 3bf31c4..ad96711 100644 --- a/internal/guesttools/drop_agent_test.go +++ b/internal/guesttools/drop_agent_test.go @@ -55,30 +55,44 @@ func TestDropAgentRoutes(t *testing.T) { set -eu [ "$1" = -l ] && [ "$2" = JavaScript ] && [ "$3" = "./drop-resolve.js" ] || exit 1 shift 3 -echo "$1" >> osascript-calls +echo "$1" >> drop-calls +window=Notes bundle=com.apple.Notes +if [ "$CASE" = stale-reference ]; then window=Finder bundle=com.apple.finder; fi case "$1" in run-drop) - [ "$#" = 4 ] && [ "$2" = event ] && [ "$3" = "$PWD/mount" ] && - [ "$4" = http://host/v1/drop-events/paste ] && [ -f "$DROP_INJECT_LOCK" ] && + [ "$#" = 3 ] && [ "$2" = event ] && + [ "$3" = http://host/v1/drop-events/paste ] && [ -f "$DROP_INJECT_LOCK" ] && [ "$REIMS_TOKEN" = fixture-secret ] || exit 1 for arg do case "$arg" in *fixture-secret*) exit 1 ;; esac; done case "$CASE" in - fast-window|fast-text|fast-photos|fast-cancelled) printf 'done\t%s\n' "$EXPECT"; exit 0 ;; + fast-text|fast-cancelled) printf 'done\t%s\n' "$EXPECT"; exit 0 ;; esac printf 'fallback\nid\t%s\t%s\t0\t0.4\t0.6\ttrue\n' "$MODE" "$DAV" case "$TARGET" in desktop) printf 'desktop\tDesktop\t%s/Desktop\t0\n' "$PWD" ;; photos) printf 'photos\tPhotos\tcom.apple.Photos\t31\n' ;; - window) printf 'window\tNotes\tcom.apple.Notes\t42\n' ;; + window) printf 'window\t%s\t%s\t42\n' "$window" "$bundle" ;; + esac + case "$CASE" in + denied-directory) printf 'Folder\tFolder\n' ;; + desktop) printf 'file.txt\tfile.txt\nFolder\tFolder\n' ;; + *) printf 'file.txt\tfile.txt\n' ;; + esac ;; + probe-mount|probe-mount-ref) + [ "$#" = 3 ] && [ "$2" = "$PWD/mount" ] && [ "$3" = "$PWD/mount/id" ] && + [ ! -e "$DROP_INJECT_LOCK" ] || exit 1 + case "$TARGET:$1" in + desktop:probe-mount|window:probe-mount-ref|photos:probe-mount-ref) ;; + *) exit 1 ;; esac - printf 'file.txt\tfile.txt\n' - if [ "$CASE" = desktop ]; then printf 'Folder\tFolder\n'; fi ;; - check-mount) - [ "$#" = 3 ] && [ "$2" = "$PWD/mount" ] && [ "$3" = "$PWD/mount/id" ] || exit 1 echo check >> mount-checks case "$CASE" in remount) [ -f remounted ] || exit 1 ;; - unhealthy-cache) exit 1 ;; + stale-reference) + [ ! -e drop_mount_denied ] || exit 1 + if [ ! -f remounted ]; then echo unhealthy; exit 0; fi ;; + unhealthy-cache) echo unhealthy; exit 0 ;; + denied-*) echo denied; exit 0 ;; esac echo ok ;; import-photos) @@ -92,11 +106,13 @@ case "$1" in paste-drop) [ "$#" = 10 ] && [ -f "$DROP_INJECT_LOCK" ] && [ "$REIMS_TOKEN" = fixture-secret ] || exit 1 for arg do case "$arg" in *fixture-secret*) exit 1 ;; esac; done - [ "$2 $3 $4 $5 $6 $7 $8 $9" = "0 0.4 0.6 42 com.apple.Notes $MODE http://host/v1/drop-events/paste id" ] + [ "$2 $3 $4 $5 $6 $7 $8 $9" = "0 0.4 0.6 42 $bundle $MODE http://host/v1/drop-events/paste id" ] touch attempted - if [ "$CASE" = cache ] || [ "$CASE" = unhealthy-cache ] || [ "$CASE" = legacy ]; then - [ "${10}" = "$PWD/cache/id/file.txt" ] && [ "$(cat "${10}")" = downloaded ] || exit 1 - else [ "${10}" = "$PWD/mount/id/file.txt" ]; fi + case "$CASE" in + cache|unhealthy-cache|legacy) + [ "${10}" = "$PWD/cache/id/file.txt" ] && [ "$(cat "${10}")" = downloaded ] || exit 1 ;; + *) [ "${10}" = "$PWD/mount/id/file.txt" ] || exit 1 ;; + esac if [ "$CASE" = closed ]; then echo cancelled else touch requested; echo pasted; fi ;; encode-ack) printf '%s|%s|%s|%s|%s' "$2" "$3" "$4" "$5" "$6" ;; @@ -109,14 +125,18 @@ esac {"photos-denied", "files", "photos", "failed|photos|Photos|Photos import blocked: allow Automation access to Photos in macOS Privacy & Security"}, {"window", "files", "window", "pasted|window|Notes|"}, {"closed", "files", "window", "cancelled|cancelled||"}, - {"fast-window", "files", "window", "pasted|window|Notes|"}, - {"fast-photos", "files", "photos", "placed|photos|Photos|"}, {"fast-text", "text", "window", "pasted|window|Notes|"}, {"fast-cancelled", "text", "desktop", "cancelled|cancelled||"}, {"cache", "files", "window", "pasted|window|Notes|"}, {"remount", "files", "window", "pasted|window|Notes|"}, + {"stale-reference", "files", "window", "pasted|window|Finder|"}, {"unhealthy-cache", "files", "window", "pasted|window|Notes|"}, {"legacy", "files", "window", "pasted|window|Notes|"}, + {"allowed-after-denial", "files", "window", "pasted|window|Notes|"}, + {"denied-file-desktop", "files", "desktop", "failed|desktop|Desktop|Network Volumes permission denied"}, + {"denied-file-window", "files", "window", "failed|window|Notes|Network Volumes permission denied"}, + {"denied-cached", "files", "desktop", "failed|desktop|Desktop|Network Volumes permission denied"}, + {"denied-directory", "files", "desktop", "failed|desktop|Desktop|Network Volumes permission denied"}, } { t.Run(tc.name, func(t *testing.T) { work := t.TempDir() @@ -131,7 +151,7 @@ set -eu PATH="$PWD:$PATH" APP_DIR=. TMP_DIR=. DROP_CACHE="$PWD/cache" DROP_MOUNT="$PWD/mount" unset REIMS_TOKEN -REIMS_TOKEN=fixture-secret REIMS_HOST_URL=http://host +REIMS_TOKEN=fixture-secret REIMS_HOST_URL=http://host REIMS_VM=guest export DROP_INJECT_LOCK="$PWD/custom-lock" DAV=true mkdir Desktop case "$CASE" in @@ -139,23 +159,45 @@ case "$CASE" in legacy) DAV=false ;; *) mkdir -p mount/id/Folder; echo file > mount/id/file.txt; echo nested > mount/id/Folder/child ;; esac +case "$CASE" in + denied-cached|allowed-after-denial|stale-reference) : > "$TMP_DIR/drop_mount_denied" ;; +esac +drop_mount_readable() { + [ ! -e "$DROP_INJECT_LOCK" ] || return 1 + touch fast-mount-check + case "$CASE" in + denied-cached) return 2 ;; + allowed-after-denial|stale-reference) return 0 ;; + *) return 1 ;; + esac +} ensure_drop_webdav_mount() { - touch mount-checked - if [ -f unmounted ]; then touch remounted; fi + if [ -f unmounted ]; then + echo remount >> drop-calls + touch remounted + fi +} +is_reims_dav_mounted() { + [ "$1" = "$DROP_MOUNT" ] && [ "$2" = /dav-drop/guest/ ] && [ -d "$DROP_MOUNT" ] && + { [ ! -e unmounted ] || [ -e remounted ]; } } unmount_shared_folder() { [ "$1" = "$DROP_MOUNT" ] || return 1 + echo unmount >> drop-calls touch unmounted } urlencode() { printf '%s' "$1"; } curl() { case "$*" in *'/v1/drop-events/ack') [ ! -e "$DROP_INJECT_LOCK" ] && [ "$8" = --data-binary ] && printf '%s' "$9" > ack ;; - *) case "$CASE:$*" in - cache:*'/v1/drop-file?drop_id=id&path=file.txt'|unhealthy-cache:*'/v1/drop-file?drop_id=id&path=file.txt'|legacy:*'/v1/file?path=file.txt') ;; - *) return 1 ;; - esac - [ "$6" = -o ] && echo downloaded > "$7" ;; + *) + printf '%s\n' "$*" >> downloads + [ ! -e "$DROP_INJECT_LOCK" ] && [ "$6" = -o ] || return 1 + case "$CASE:$8" in + cache:*'/v1/drop-file?drop_id=id&path=file.txt'|unhealthy-cache:*'/v1/drop-file?drop_id=id&path=file.txt'|legacy:*'/v1/file?path=file.txt') + echo downloaded > "$7" ;; + *) return 1 ;; + esac ;; esac } process_drop_event event @@ -163,21 +205,47 @@ process_drop_event event [ ! -e "$DROP_INJECT_LOCK" ] [ ! -e "$TMP_DIR/drop_text.$$" ] case "$CASE" in - fast-*) [ "$(wc -l < osascript-calls)" -eq 1 ] && [ "$(cat osascript-calls)" = run-drop ]; exit $? ;; + fast-*) [ "$(wc -l < drop-calls)" -eq 1 ] && [ "$(cat drop-calls)" = run-drop ]; exit $? ;; esac -if [ "$TARGET" = window ]; then [ -f attempted ]; else [ ! -e attempted ]; fi -if [ "$TARGET" = window ] && [ "$CASE" != closed ]; then [ -f requested ]; else [ ! -e requested ]; fi +case "$CASE:$TARGET" in + denied-*:*) [ ! -e attempted ] ;; + *:window) [ -f attempted ] ;; + *) [ ! -e attempted ] ;; +esac +if [ -f attempted ] && [ "$CASE" != closed ]; then [ -f requested ]; else [ ! -e requested ]; fi if [ "$CASE" = photos ]; then [ -f imported ]; else [ ! -e imported ]; fi -if [ "$MODE" = files ] && [ "$DAV" = true ]; then [ -f mount-checked ]; fi -if [ "$CASE" = remount ] || [ "$CASE" = unhealthy-cache ]; then - [ -f unmounted ] && [ -f remounted ] || exit 1 - [ "$(wc -l < mount-checks)" -eq 2 ] -fi -if [ "$CASE" = desktop ]; then - [ "$(cat Desktop/file.txt)" = file ] - [ "$(cat Desktop/Folder/child)" = nested ] - [ ! -e "$DROP_CACHE" ] -fi +case "$CASE" in + remount|stale-reference|unhealthy-cache) + [ -f unmounted ] && [ -f remounted ] || exit 1 + [ "$(wc -l < mount-checks)" -eq 2 ] ;; + legacy|cache|denied-cached) [ ! -e mount-checks ] ;; + *) [ "$(wc -l < mount-checks)" -eq 1 ] ;; +esac +case "$CASE" in + denied-*) + [ -f "$TMP_DIR/drop_mount_denied" ] + [ ! -e unmounted ] && [ ! -e remounted ] || exit 1 + [ ! -e downloads ] && [ ! -e "$DROP_CACHE" ] || exit 1 + [ ! -e Desktop/file.txt ] && [ ! -e Desktop/Folder ] || exit 1 ;; + *) [ ! -e "$TMP_DIR/drop_mount_denied" ] ;; +esac +case "$CASE" in + desktop) + [ "$(cat Desktop/file.txt)" = file ] + [ "$(cat Desktop/Folder/child)" = nested ] + [ ! -e "$DROP_CACHE" ] && [ ! -e downloads ] ;; + window|allowed-after-denial) [ ! -e downloads ] ;; + stale-reference) + [ ! -e downloads ] && [ ! -e "$DROP_CACHE" ] || exit 1 + expected_calls=$(printf '%s\n' run-drop probe-mount-ref unmount remount probe-mount-ref paste-drop encode-ack) + [ "$(cat drop-calls)" = "$expected_calls" ] ;; +esac +case "$CASE" in + denied-cached) + [ -f fast-mount-check ] + ! grep -Eq '^probe-mount(-ref)?$' drop-calls ;; + allowed-after-denial|stale-reference) [ -f fast-mount-check ] ;; +esac `) if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("sh: %v\n%s", err, out) diff --git a/internal/guesttools/drop_resolve.js b/internal/guesttools/drop_resolve.js index dae922d..8343139 100644 --- a/internal/guesttools/drop_resolve.js +++ b/internal/guesttools/drop_resolve.js @@ -320,45 +320,22 @@ function importPhotos(paths) { return 'ok' } -function photosError(err) { - const msg = String(err && err.message || err || '').replace(/[\r\n\t]+/g, ' ').trim() - if (/1743|not authorized|permission|privilege/i.test(msg)) return 'Photos import blocked: allow Automation access to Photos in macOS Privacy & Security' - return msg ? 'Photos import failed: ' + msg.slice(0, 140) : 'Photos import failed' -} - -function runDrop(eventFile, mount, url) { +function runDrop(eventFile, url) { const ev = parseEventData(eventFile) const hitArgs = [ev.display_index, ev.norm_x, ev.norm_y, ev.in_image].map(String) const target = resolve(hitArgs) const [kind, label, meta, expected] = target.split('\t') - function done(status) { + function done(status, error = '') { return 'done\t' + encodeAck(ev.drop_id, status, status === 'cancelled' ? 'cancelled' : kind, - status === 'cancelled' ? '' : label, '', []) - } - function perform(mode, paths) { - try { - if (kind === 'photos') { - importPhotos(paths) - return done('placed') - } - return done(pasteCore(hitArgs, expected, meta, mode, url, ev.drop_id, paths)) - } catch (err) { - return 'done\t' + encodeAck(ev.drop_id, 'failed', kind, label, - kind === 'photos' ? photosError(err) : 'Paste failed', []) - } + status === 'cancelled' ? '' : label, error, []) } if (kind === 'none' || (ev.kind === 'text' && kind !== 'window')) return done('cancelled') - if (ev.kind === 'text') return perform('text-raw', [ev.text]) - if ((kind === 'window' || kind === 'photos') && ev.webdav_drop && mount) { - const dir = mount + '/' + ev.drop_id - const fm = $.NSFileManager.defaultManager - const dirRef = Ref() - const paths = ev.items.map(src => dir + '/' + src) - if (fm.fileExistsAtPathIsDirectory(dir, dirRef) && dirRef[0] && mountHealthy([mount, dir]) && - paths.every(p => fm.fileExistsAtPath(p))) { - return perform('files', paths) - } + if (ev.kind === 'text') { + try { + return done(pasteCore(hitArgs, expected, meta, 'text-raw', url, ev.drop_id, [ev.text])) + } catch (_) { return done('failed', 'Paste failed') } } + // The shell probes the mount after releasing the drop injection lock. const [header, ...items] = eventLines(ev) return ['fallback', header, target].concat(items).join('\n') } @@ -458,25 +435,28 @@ function validateClipArchive(manifestFile, entriesFile) { return 'ok' } -function mountedClipboardSourcesReadable(paths) { +function mountedSourcesStatus(paths) { // Metadata can remain visible when WebDAV can no longer serve the item. // Give the entire probe a deadline, without downloading the selection. const check = ` + use Errno qw(EPERM EACCES); alarm 5; + sub failed { exit(($! == EPERM || $! == EACCES) ? 2 : 1) } for my $path (@ARGV) { - if (-d $path) { - opendir(my $dir, $path) or exit 1; + stat($path) or failed(); + if (-d _) { + opendir(my $dir, $path) or failed(); while (1) { $! = 0; my $name = readdir($dir); - exit 1 if !defined($name) && $!; + failed() if !defined($name) && $!; last if !defined($name) || ($name ne '.' && $name ne '..'); } - closedir($dir) or exit 1; - } elsif (-f $path) { - open(my $file, '<:raw', $path) or exit 1; - defined(sysread($file, my $byte, 1)) or exit 1; - close($file) or exit 1; + closedir($dir) or failed(); + } elsif (-f _) { + open(my $file, '<:raw', $path) or failed(); + defined(sysread($file, my $byte, 1)) or failed(); + close($file) or failed(); } else { exit 1; } @@ -490,8 +470,38 @@ function mountedClipboardSourcesReadable(paths) { task.standardError = $.NSFileHandle.fileHandleWithNullDevice task.launch task.waitUntilExit - return task.terminationStatus === 0 - } catch (_) { return false } + if (task.terminationStatus === 0) return 'ok' + return task.terminationStatus === 2 ? 'denied' : 'unreadable' + } catch (_) { return 'unreadable' } +} + +function isMountPermissionError(error) { + const posixDenied = err => err && !err.isNil?.() && err.domain && + ObjC.unwrap(err.domain) === 'NSPOSIXErrorDomain' && [1, 13].includes(Number(err.code)) + if (!error || error.isNil?.()) return false + if (error.domain && ObjC.unwrap(error.domain) === 'NSCocoaErrorDomain' && Number(error.code) === 257) return true + const info = error.userInfo + return posixDenied(error) || (info && !info.isNil?.() && posixDenied(info.objectForKey($.NSUnderlyingErrorKey))) +} + +function probeMount(paths, requireRef) { + if (!paths.length || paths.some(path => !path)) return 'unhealthy' + const fm = $.NSFileManager.defaultManager + for (const path of paths) { + // Passing Ref() for NSError** can crash JXA on macOS Tahoe. + const err = $() + try { + const entries = fm.contentsOfDirectoryAtPathError(path, err) + if (entries && !entries.isNil?.()) continue + if (isMountPermissionError(err)) return 'denied' + } catch (failure) { + if (isMountPermissionError(failure)) return 'denied' + } + // If the bridge did not expose NSError, recover errno without prompting again. + return mountedSourcesStatus([path]) === 'denied' ? 'denied' : 'unhealthy' + } + if (requireRef && !mountHealthy(paths)) return 'unhealthy' + return 'ok' } function writeClipFiles(manifestFile, mount, expectedCount, cached = false) { @@ -502,12 +512,16 @@ function writeClipFiles(manifestFile, mount, expectedCount, cached = false) { const isDir = Ref() const exists = () => fm.fileExistsAtPathIsDirectory(dir, isDir) && isDir[0] if (!exists()) { - fm.contentsOfDirectoryAtPathError(mount, null) - if (!exists()) return 'remount' + if (cached) return 'remount' + const access = mountedSourcesStatus([mount]) + if (access === 'denied') return access + if (access !== 'ok' || !exists()) return 'remount' } const paths = ev.items.map(name => dir + '/' + name) - if ((!cached && !mountHealthy([mount, dir])) || !paths.every(p => fm.fileExistsAtPath(p))) return 'remount' - if (!cached && !mountedClipboardSourcesReadable(paths)) return 'unreadable' + const access = cached ? 'ok' : mountedSourcesStatus(paths) + if (access === 'denied') return access + if (!paths.every(p => fm.fileExistsAtPath(p)) || (!cached && !mountHealthy([mount, dir]))) return 'remount' + if (access !== 'ok') return access const urls = paths.map(p => $.NSURL.fileURLWithPath(p).absoluteString) const newItems = urls.map(url => { const item = $.NSPasteboardItem.alloc.init @@ -545,6 +559,8 @@ function run(argv) { if (mode === 'write-clip-files') return writeClipFiles(args[0], args[1], args[2], args[3] === 'cache') if (mode === 'run-drop') return runDrop(...args) if (mode === 'resolve') return resolve(args) + if (mode === 'probe-mount') return probeMount(args) + if (mode === 'probe-mount-ref') return probeMount(args, true) if (mode === 'check-mount') { if (!mountHealthy(args)) throw Error('Unreachable mount') return 'ok' diff --git a/internal/guesttools/drop_status_test.go b/internal/guesttools/drop_status_test.go new file mode 100644 index 0000000..b15352f --- /dev/null +++ b/internal/guesttools/drop_status_test.go @@ -0,0 +1,58 @@ +package guesttools + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestDropMountDenialFollowsFreshGuestHeartbeat(t *testing.T) { + const maxAge = 15 * time.Second + srv := NewTransportServer(nil) + guest := VMConfig{VMName: "guest", Token: "guest-token"} + peer := VMConfig{VMName: "peer", Token: "peer-token"} + srv.RegisterVM(guest) + srv.RegisterVM(peer) + + report := func(cfg VMConfig, body string) { + t.Helper() + req := httptest.NewRequest(http.MethodPost, "/v1/status", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+cfg.Token) + w := httptest.NewRecorder() + srv.handleStatus(w, req) + if w.Code != http.StatusOK { + t.Fatalf("guest heartbeat: status %d: %s", w.Code, w.Body) + } + } + check := func(cfg VMConfig, connected, denied bool) { + t.Helper() + got := srv.Status(cfg.VMName, maxAge) + if got.Connected != connected || got.DropMountDenied != denied { + t.Fatalf("%s status: connected/denied = %t/%t, want %t/%t", cfg.VMName, got.Connected, got.DropMountDenied, connected, denied) + } + } + + check(guest, false, false) + report(peer, `{}`) + report(guest, `{"drop_mount_denied":true}`) + check(guest, true, true) + check(peer, true, false) + + // Clipboard or drop activity can keep the guest connected after its last heartbeat expires. + srv.mu.Lock() + vm := srv.vms[normalizeVMRegistryKey(guest.VMName)] + vm.lastStatus = time.Now().Add(-2 * maxAge) + srv.mu.Unlock() + check(guest, true, false) + + report(guest, `{"drop_mount_denied":true}`) + check(guest, true, true) + report(guest, `{"drop_mount_denied":false}`) + check(guest, true, false) + report(guest, `{"drop_mount_denied":true}`) + check(guest, true, true) + report(guest, `{}`) + check(guest, true, false) +} diff --git a/internal/guesttools/folder_share.go b/internal/guesttools/folder_share.go index 186be50..772ebcc 100644 --- a/internal/guesttools/folder_share.go +++ b/internal/guesttools/folder_share.go @@ -25,8 +25,9 @@ const WindowReportAgentVersion = 17 const PasteReadyAgentVersion = 18 const FileClipboardReadinessAgentVersion = 19 const SharedFolderWebDAVAgentVersion = 20 +const DropNetworkVolumesAgentVersion = 21 -const CurrentAgentVersion = SharedFolderWebDAVAgentVersion +const CurrentAgentVersion = DropNetworkVolumesAgentVersion type SharedFolderConfig struct { ID string `json:"id"` diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index c69d172..e6a08b2 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -407,6 +407,7 @@ mount_authenticated_webdav() ( ensure_drop_webdav_mount() { [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] && [ -n "$REIMS_VM" ] || return 0 if is_reims_dav_mounted "$DROP_MOUNT" "/dav-drop/$(urlencode "$REIMS_VM")/"; then + [ ! -f "$TMP_DIR/drop_mount_denied" ] || return 0 mount 2>/dev/null | awk -v mp="$DROP_MOUNT" ' index($0, " on " mp " (") && /[(,] *nobrowse *[,)]/ { found=1 } END { exit !found }' || return 0 @@ -670,6 +671,13 @@ apply_host_config() { report_status() { [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 + drop_mount_denied=false + if [ -n "${TMP_DIR:-}" ] && [ -f "$TMP_DIR/drop_mount_denied" ]; then + if drop_webdav_mounted && drop_mount_readable; then + rm -f "$TMP_DIR/drop_mount_denied" || true + fi + [ ! -f "$TMP_DIR/drop_mount_denied" ] || drop_mount_denied=true + fi host_dns_active=false host_dns_config_stale=false dns_plist=/Library/LaunchDaemons/com.reimsgo.dns-proxy.plist @@ -685,11 +693,13 @@ report_status() { fi fi timezone_applied=$(current_timezone) - curl -fsS -m "${1:-3}" -X POST \ + if curl -fsS -m "${1:-3}" -X POST \ -H "Authorization: Bearer $REIMS_TOKEN" \ -H "Content-Type: application/json" \ - -d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":` + strconv.Itoa(CurrentAgentVersion) + `,\"keymap_active\":$keymap_active,\"timezone_applied\":\"$timezone_applied\",\"timezone_helper_ready\":$timezone_helper_ready,\"timezone_error\":\"$timezone_error\",\"host_dns_active\":$host_dns_active,\"host_dns_config_stale\":$host_dns_config_stale}" \ - "$REIMS_HOST_URL/v1/status" >/dev/null 2>&1 || true + -d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":` + strconv.Itoa(CurrentAgentVersion) + `,\"keymap_active\":$keymap_active,\"timezone_applied\":\"$timezone_applied\",\"timezone_helper_ready\":$timezone_helper_ready,\"timezone_error\":\"$timezone_error\",\"host_dns_active\":$host_dns_active,\"host_dns_config_stale\":$host_dns_config_stale,\"drop_mount_denied\":$drop_mount_denied}" \ + "$REIMS_HOST_URL/v1/status" >/dev/null 2>&1; then + reported_drop_mount_denied="$drop_mount_denied" + fi } read_local_clipboard() { @@ -795,6 +805,7 @@ write_local_files() ( case "$res" in ok) return 0 ;; unreadable) return 2 ;; + denied) return 3 ;; remount) ;; *) return 1 ;; esac @@ -1310,6 +1321,26 @@ sync_clipboard() { if [ "$new_kind" = files ]; then delivery=0 write_local_files "$clip_out" "$read_cc" || delivery=$? + if [ "$delivery" = 3 ]; then + # The permission dialog can wait for the user while IME keeps running. + release_clip_lock + drop_access=$(probe_drop_mount) || drop_access=unhealthy + if ! acquire_clip_lock; then + defer_file_delivery + return 0 + fi + if clipboard_poll_interrupted; then + defer_file_delivery + release_clip_lock + return 0 + fi + delivery=2 + if [ "$drop_access" = ok ] && [ -n "$read_cc" ]; then + delivery=0 + write_local_files "$clip_out" "$read_cc" || delivery=$? + [ "$delivery" != 3 ] || delivery=2 + fi + fi if [ "$delivery" = 2 ] && [ -n "$read_cc" ]; then read_clip_file_config if [ "$archive_bytes" -gt 0 ]; then @@ -1539,6 +1570,12 @@ while :; do ensure_webdav_mount ensure_drop_webdav_mount report_status + else + drop_mount_denied=false + [ ! -f "$TMP_DIR/drop_mount_denied" ] || drop_mount_denied=true + if [ "$drop_mount_denied" != "${reported_drop_mount_denied:-false}" ]; then + report_status + fi fi if [ "$mount_mode" != "webdav" ] && [ $((tick % 2)) -eq 0 ]; then run_file_sync_async diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index 5a00e18..7bc0436 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -127,6 +127,7 @@ type GuestStatus struct { KeymapActive bool `json:"keymap_active"` Connected bool `json:"connected"` MountMode string `json:"mount_mode,omitempty"` // "webdav" | "sync" + DropMountDenied bool `json:"drop_mount_denied"` PreventSleep bool `json:"prevent_sleep"` SleepActive bool `json:"sleep_active"` AgentVersion int `json:"agent_version,omitempty"` @@ -262,6 +263,7 @@ type registeredVM struct { keymapActive bool // Carrier confirmed by a status report since the last disconnect. lastStatus time.Time mountMode string + dropMountDenied bool sleepActive bool agentVersion int lastSeen time.Time @@ -884,6 +886,7 @@ func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus { KeymapActive: connected && vm.keymapActive, Connected: connected, MountMode: vm.mountMode, + DropMountDenied: freshStatus && vm.dropMountDenied, PreventSleep: vm.preventSleep, SleepActive: connected && vm.sleepActive, AgentVersion: vm.agentVersion, @@ -1075,6 +1078,7 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { var req struct { KeymapActive bool `json:"keymap_active"` MountMode string `json:"mount_mode"` + DropMountDenied bool `json:"drop_mount_denied"` SleepActive bool `json:"sleep_active"` AgentVersion int `json:"agent_version"` TimezoneApplied string `json:"timezone_applied"` @@ -1108,6 +1112,7 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { if mode != "" { cur.mountMode = mode } + cur.dropMountDenied = req.DropMountDenied cur.sleepActive = req.SleepActive cur.hostDNSReported = req.HostDNSActive != nil cur.hostDNSActive = cur.hostDNSReported && *req.HostDNSActive diff --git a/internal/guesttools/testdata/pasteboard.cjs b/internal/guesttools/testdata/pasteboard.cjs index 479268a..978beaa 100644 --- a/internal/guesttools/testdata/pasteboard.cjs +++ b/internal/guesttools/testdata/pasteboard.cjs @@ -6,7 +6,9 @@ const {pathToFileURL} = require('node:url') const [resolver, ...argv] = process.argv.slice(2) const stateFile = 'test-pasteboard.json' -const state = fs.existsSync(stateFile) ? JSON.parse(fs.readFileSync(stateFile)) : {changeCount: 0, items: []} +const readFixture = (path, fallback) => fs.existsSync(path) ? JSON.parse(fs.readFileSync(path)) : fallback +const state = readFixture(stateFile, {changeCount: 0, items: []}) +const missingReference = 'test-missing-file-reference' const nil = {isNil: () => true} const wrap = js => js == null ? nil : { js, isNil: () => false, dataUsingEncoding: () => js, @@ -52,11 +54,12 @@ class FixtureTask { if (this.launchPath === '/usr/bin/perl') { const [, , , ...paths] = this.arguments fs.writeFileSync('test-hosted-probe.json', JSON.stringify(paths)) - const denied = fs.existsSync('test-hosted-probe-denied.json') - ? JSON.parse(fs.readFileSync('test-hosted-probe-denied.json')) : [] + const unreadable = readFixture('test-hosted-probe-denied.json', []) + const errors = readFixture('test-hosted-probe-errors.json', {}) try { for (const path of paths) { - if (denied.includes(path)) throw Error('Cannot read hosted clipboard source') + if (errors[path]) throw Object.assign(Error('Cannot read hosted clipboard source'), {code: errors[path]}) + if (unreadable.includes(path)) throw Error('Cannot read hosted clipboard source') const info = fs.statSync(path) if (info.isDirectory()) { const dir = fs.opendirSync(path) @@ -69,7 +72,7 @@ class FixtureTask { } } this.terminationStatus = 0 - } catch (_) { this.terminationStatus = 1 } + } catch (err) { this.terminationStatus = ['EPERM', 'EACCES'].includes(err.code) ? 2 : 1 } return } // The host reads the staged clipboard and may allow a new user copy before it releases the ACK. @@ -84,16 +87,36 @@ class FixtureTask { } } -const $ = Object.assign(value => typeof value === 'string' ? wrap(value) : value, { +const errorPointers = new WeakSet() +const underlyingErrorKey = 'NSUnderlyingError' +function nativeError({domain, code, underlying}) { + return { + domain: wrap(domain), code, + userInfo: {objectForKey: key => key === underlyingErrorKey && underlying ? nativeError(underlying) : nil} + } +} + +const $ = Object.assign(value => { + if (value !== undefined) return typeof value === 'string' ? wrap(value) : value + const error = {isNil() { return !this.domain }} + errorPointers.add(error) + return error +}, { NSPasteboard: {generalPasteboard: pasteboard}, NSPasteboardItem: {alloc: {get init() { return item() }}}, NSPasteboardTypeFileURL: 'public.file-url', NSPasteboardTypeString: 'public.utf8-plain-text', + NSUnderlyingErrorKey: underlyingErrorKey, NSData: {data: wrap('')}, NSString: {stringWithContentsOfFileEncodingError: path => wrap(fs.readFileSync(path, 'utf8'))}, NSURL: { fileURLWithPath: path => ({ - absoluteString: wrap(pathToFileURL(path).href), fileReferenceURL: fs.existsSync(path) ? wrap(path) : nil + absoluteString: wrap(pathToFileURL(path).href), + get fileReferenceURL() { + fs.appendFileSync('test-mount-reference-probe.log', `${path}\n`) + if (fs.existsSync(missingReference) && fs.readFileSync(missingReference, 'utf8') === path) return nil + return fs.existsSync(path) ? wrap(path) : nil + } }), URLWithString: raw => { const url = new URL(raw) @@ -109,7 +132,23 @@ const $ = Object.assign(value => typeof value === 'string' ? wrap(value) : value dir[0] = fs.statSync(path, {throwIfNoEntry: false})?.isDirectory() ?? false return fs.existsSync(path) }, - contentsOfDirectoryAtPathError: path => fs.readdirSync(path), + contentsOfDirectoryAtPathError(path, err) { + const boxed = errorPointers.has(err) + fs.appendFileSync('test-mount-directory-probe.log', `${path}\t${boxed ? '$()' : 'invalid'}\n`) + if (!boxed) throw Error('Directory enumeration requires a boxed NSError') + const errors = readFixture('test-mount-directory-errors.json', {}) + if (Object.hasOwn(errors, path)) { + if (errors[path]) Object.assign(err, nativeError(errors[path])) + return nil + } + try { + return array(fs.readdirSync(path).map(wrap)) + } catch (failure) { + const code = failure.code === 'ENOENT' ? 260 : 256 + Object.assign(err, nativeError({domain: 'NSCocoaErrorDomain', code})) + return nil + } + }, fileExistsAtPath: fs.existsSync }}, NSDate: {dateWithTimeIntervalSinceNow: seconds => seconds}, diff --git a/internal/macos/reims/reims.go b/internal/macos/reims/reims.go index 0a0e7cf..89ffe8f 100644 --- a/internal/macos/reims/reims.go +++ b/internal/macos/reims/reims.go @@ -116,6 +116,8 @@ type VMDetail struct { GuestToolsPreventSleep bool `json:"guest_tools_prevent_sleep"` GuestToolsSleepActive bool `json:"guest_tools_sleep_active"` GuestToolsAgentVersion int `json:"guest_tools_agent_version,omitempty"` + // GuestToolsDropAccessDenied reflects the guest's live Network Volumes permission status. + GuestToolsDropAccessDenied bool `json:"guest_tools_drop_access_denied"` // GuestToolsDisabled is set when the Guest Tools plugin is switched off. GuestToolsDisabled bool `json:"guest_tools_disabled,omitempty"` SharedDir string `json:"shared_dir,omitempty"` diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index 0644a8e..bc3cee7 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -231,6 +231,8 @@ "specNetSSHTip": "Shares this PC’s network connection; SSH on port {port}", "specNetOffTip": "The VM has no network", "gtStatusConnected": "Connected", + "gtDropAccessLimited": "File drop limited", + "gtDropAccessHint": "File drops transfer via WebDAV. Enable Network Volumes for sh in macOS System Settings → Privacy & Security → Files and Folders", "gtStatusWaiting": "Not connected", "gtStatusWaitingTip": "Connects once the install command has run in macOS", "gtStatusEnabled": "Enabled", diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index 33c0c70..610ce6e 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -231,6 +231,8 @@ "specNetSSHTip": "与宿主共享网络连接,SSH 端口 {port}", "specNetOffTip": "虚拟机没有网络", "gtStatusConnected": "已连接", + "gtDropAccessLimited": "文件拖放受限", + "gtDropAccessHint": "拖放通过 WebDAV 传输文件,请在 macOS「系统设置 → 隐私与安全性 → 文件与文件夹」中开启 sh 的「网络宗卷」权限", "gtStatusWaiting": "未连接", "gtStatusWaitingTip": "在 macOS 里运行安装命令后会自动连接", "gtStatusEnabled": "已启用",