* feat(plugin,host,ui): add agent session takeover, protected-phase confirmation, and autoinstall host foundation * feat(macos,ui,cli): add offline REIMSPROV first-boot provisioning to skip Setup Assistant (#129) Builds a per-VM read-only REIMSPROV disk image containing a pure-Go XAR Distribution flat package (provision.pkg) and an offline Recovery fallback script (provision-offline.sh). Passwords are hashed in memory to Apple SALTED-SHA512-PBKDF2 bplist00 ShadowHashData (never persisted in plaintext, no auto-login or NOPASSWD sudo). Uses native OpenDirectory.framework (JXA NSData) + dseditgroup under SIP-enabled live bootinstalld and dslocal plist + PlistBuddy under offline Recovery, skips Setup Assistant and Keyboard Setup Assistant, pre-stages Guest Tools, integrates with CreateWizard / VMPage / vm provision CLI / StartAutoInstall, and zero-wipes on finish_install, normal cold start, or DeleteVM. * feat(autoinstall,host,ui): add input-locked session shield, recovery-only mode, and restart grace cap Adds the real-machine end-to-end verified baseline for automatic macOS installation: (1) takeover_policy 'lock' with transparent Win32 VM client-area input shield, low-level key/mouse lock preserving host escape shortcuts (Alt+Tab/Alt+Esc/Win), HUD & UI Pause/Resume controls, and write guards while paused; (2) decoupled recovery_only vs full (REIMSPROV) modes in StartAutoInstall, CreateWizard, and VMAutoInstallPanel; (3) graceful_timeout_sec cap (default 10s) on automated built-in macOS host/vm.restart so Setup Assistant/Login Window restarts do not stall 90s on ACPI; (4) additional modifier aliases in console manager and agent-session/telemetry cleanup on VM deletion. * feat(autoinstall,overlay,plugin): add built-in macOS auto-install plugin, dynamic island overlay, and review fixes * fix(app,host,macos,ui): address PR #134 automated review findings - Frontend & i18n: - Fix UTF-8/GBK mojibake in VMPage.tsx. - Emit reims:confirm-resolved on timeout/cancel/resolve so frontend modals auto-close and surface errors cleanly; stop submitCreate from continuing after PrepareVMProvision failure. - Gate AutoInstallPanel RapidOCR download button on preflight can_download_ocr when pinned default assets are unavailable. - App / Sessions / Confirm / Lifecycle: - Add 30s denial cooldown for protected-phase confirmation prompts and revoke (pluginID, vmKey) grants on non-completed session exits. - Fix sessionOverlay / activeAgentSessions data race, remove duplicate permission-denied invocation, guard against clobbering other sessions or completed overlays, and unify VM key normalization. - Grant protected-phase confirmation and attach lock-mode session + watcher when resuming auto-install without an active session. - Unify FinishInstall and host/vm.finishInstall result handling and persist .reims-go-provision-ready across restarts. - Preserve non-timeout stop errors in restartMacOSVMLocked instead of force-killing. - Host Takeover Hooks: - Require both keyboard and mouse WH_*_LL hooks (rolling back partial installs), initialize thread message queue before ready, reset started state on error/exit for retry, and report hook failures. - macOS Provisioning & Autoinstall Engine: - Track REIMSPROV staged/wipe-pending/ready lifecycle markers, exclude "restore" recovery marker from re-attaching REIMSPROV, fail explicitly on offline admin plist creation failure, and report wipe failures. - Serialize per-VM Start/Stop/Resume with stop generation tokens, guard ROI fast-path against maxDim overflow, switch hostclient early-event buffer to FIFO eviction, fix untyped nil Engine return, tighten negation & high-risk fuzzy matching, preserve ackedQemuErrors across RebootWindow resets, and re-orient/expire stale inherited running checkpoints. - Document verified Windows SDK IDL vtable slots for WinOCR (live-tested on Windows) and add regression tests across app, host, macosdriver, startprep, installer, and autoinstall packages. * fix(app,cli,host,macos,ui): address PR #134 second automated review findings - CLI & Desktop Control Channel: - Add __reims_host__ / autoinstall desktop control channel with data_root verification so CLI status, resume, and stop talk directly to the live desktop runner instead of splitting checkpoint state or launching doomed short-lived CLI runners. - Merge live runners with on-disk checkpoints when listing status without a VM argument. - App Sessions, Confirmations, Downloads & Telemetry: - Scope single-VM not_authorized errors to the target VM in handleSessionBegin and resolveComputerUseVM so active sessions on other VMs are not aborted. - Exclude stopped and suspended VMs from hasUnboundAgentSession fast-polling. - Revoke protected-phase grants when a VM disappears from poll results. - Require manifest Secret:true validation before storing auto-install passwords and remove the unsafe default account_password fallback. - Reject userinfo URLs in allow_custom_mirror, gate custom-mirror exemption strictly on plugin.ErrNetOriginNotDeclared, and keep redirect SSRF checks enabled on loopback custom mirrors. - Preserve VM telemetry milestones across suspend-resume and Win10 cold-reboot restarts while still resetting on fresh cold boots. - Log a warning when Guest Tools bridge is unavailable while preparing REIMSPROV. - Clarify CallHostAPI authorization/audit contract and add regression test proving built-in plugins enforce catalog permissions and audit logging. - Host Takeover & Guest Tools: - Track locked mouse button presses via a 5-button bitmask so ButtonUp events from drags started outside the VM window are never swallowed. - Align active-window-reporter.js permissions to 0o100755 across ToolsDiskFiles, ToolsProvisionFiles, and postinstall. - macOS Provisioning & Autoinstall Engine (OCR / Vision / Rules / Runner): - Never delete an unwiped REIMSPROV image on OpenFile/Write/Sync failure; persist wipe-pending marker and return error for retry. - Harden live postinstall preference writes with chmod 600, plutil -lint, chown, and cfprefsd flush. - Rewrite Windows RapidOCR C ABI structs and result extraction to match RapidAI/RapidOcrOnnx@675e73fe4c include/OcrLiteCApi.h:27-70 and src/OcrLiteCApi.cpp:12-160 (5-arg OcrInit verified). - Inspect PE32/PE32+ IMAGE_DIRECTORY_ENTRY_IMPORT directly to require onnxruntime.dll only for dynamically linked RapidOcrOnnx.dll builds. - Validate cfg.VM and use collision-free SHA-256-suffixed checkpoint paths with read fallback; redact PII/paths/UUIDs/MACs/IPs/tokens in diagnostic summaries; snapshot checkpoints before releasing r.mu for serialized disk I/O. - Add contrast/border/focus-ring ok return to DetectInputFieldNearLabel, enforce mask-dots verification in fillAccountForm and login screens, refuse blind password typing on clock-only lock screens, confirm shell readiness before typing install.sh, and prefer isolated button lines over modal prose in FindHit. - Frontend: - Require explicit Apple SLA confirmation in both recovery_only and full modes across AutoInstallPanel and CreateWizard, with unit tests in frontend/scripts/test-autoinstall.mjs. * fix(app,cli,host,macos,ui): address PR #134 third automated review findings Addresses all confirmed findings from Review #6204465334 (commit d516350) with targeted regression tests and hardens verified COM vtable bindings: - App & Session Lifecycle: - Track hostPaused separately in agentSession so plugin host/session.update (paused_for_user=false) cannot clear physical user takeover or explicit PauseAgentSession holds; only host ResumeAgentSession or timed takeover expiry clears them. - Give each auto-install session watcher a monotonic watchGen + cancelable child context so restarting/resuming auto-install on the same VM cancels any superseded watcher and prevents stale timeout or secret cleanup. - Bound fast 500ms unbound-PID discovery for running VMs to sessionDiscoverGraceWindow via unboundSince (refreshed on restart/rebind). - Keep non-blocking buffered confirm resolution send inside confirmMu for clear mutual exclusion with cancelPendingConfirmations. - Clear cold-reboot telemetry preserveNextBoot via defer on all early-return and StartVM-failure paths in watchColdReboot. - Rebuild REIMSPROV with current StartAutoInstall credentials (preserving install_guest_tools) whenever VM is stopped instead of reusing stale images. - CLI & macOS Provisioning / StartPrep: - Refuse `vm provision --clear` and overwriting existing REIMSPROV while the VM is running or paused. - Guard live "/" root in postinstall against macOS Recovery/Installer (/System/Installation/CDIS), forbid "/" in provision-offline.sh, and scope chmod 644 strictly to com.apple.keyboardtype.plist. - Reject unknown -* options in REIMSHELP/install.sh (including after --erase). - Defer clearing the one-shot REIMSPROV staged marker until after setExtraArgs (startprep) and StartWithCompat (macosdriver) succeed. - Preserve pending RestartFrom guards in AdvancePostInstallHandoff when checkpoint is already at StepDesktop. - Host Input & Session Overlay: - Filter injected keyboard events (LLKHF_INJECTED / LLKHF_LOWER_IL_INJECTED) in locked-input mode consistently with the mouse hook. - Clean up exited overlay entries in entry.run() and recreate dead entries on Manager.Upsert when CreateWindowExW fails or exits early. - Cache the static island base surface (shell + icons + DirectWrite text) and measured text metrics across breathing frames, raising timerBreathMs to 100ms. - Replace magic Direct2D/DirectWrite vtable indices with named d2d1.h / dwrite.h constants, check EndDraw HRESULT, and add a live Windows DirectWrite rendering smoke test. - Autoinstall OCR, Rules, Watchdog & Runner: - Persist and verify a per-file SHA-256 manifest.json in <dataDir>/ocr/ before loading RapidOcrOnnx.dll / onnxruntime.dll; reject duplicate whitelisted basenames in offline zip imports. - Signal WinOCREngine.Close() before acquiring e.mu and add bounded wait + channel wakeup in Recognize so Close() immediately cancels in-flight OCR. - Fall back to installed RapidOCR when WinOCR initialization fails in Open(), and distinguish needs_rapidocr_import from needs_rapidocr_download in Probe. - Pause instead of pressing Return when post-TypeSecret login screenshot fails. - Re-baseline ColdRebootCount in Watchdog.ResetRebootWindow / ResetAfterResume. - Tighten recovery.main specificity (drop bare "Disk Utility"), guard 4-5 char pure-ASCII needles from sliding-window fuzzy collisions, use Unicode word boundaries for short names (<4 runes) in RedactDiagnosticText, and honor rule verify.wait_change_ms with early exit on visual frame diff. * fix(autoinstall): handle CJK short-name redaction, sh-3.2 prompt bound, and OCR re-import pruning
314 lines
13 KiB
Go
314 lines
13 KiB
Go
package plugin
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"regexp"
|
|
"sort"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func readFrontendContract(t *testing.T, rel string) string {
|
|
t.Helper()
|
|
raw, err := os.ReadFile(filepath.Join("..", "..", "frontend", "src", filepath.FromSlash(rel)))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return string(raw)
|
|
}
|
|
|
|
func tsArray(t *testing.T, src, name string) []string {
|
|
t.Helper()
|
|
m := regexp.MustCompile(`export const ` + name + ` = \[([\s\S]*?)\] as const`).FindStringSubmatch(src)
|
|
if m == nil {
|
|
t.Fatalf("cannot find %s in frontend contract", name)
|
|
}
|
|
var out []string
|
|
for _, s := range regexp.MustCompile(`'([^']+)'`).FindAllStringSubmatch(m[1], -1) {
|
|
out = append(out, s[1])
|
|
}
|
|
sort.Strings(out)
|
|
return out
|
|
}
|
|
|
|
func tsVersion(t *testing.T, src, name string) string {
|
|
t.Helper()
|
|
m := regexp.MustCompile(name + `\s*=\s*'([^']+)'`).FindStringSubmatch(src)
|
|
if m == nil {
|
|
t.Fatalf("cannot find %s", name)
|
|
}
|
|
return m[1]
|
|
}
|
|
|
|
func sorted(in []string) []string {
|
|
out := append([]string(nil), in...)
|
|
sort.Strings(out)
|
|
return out
|
|
}
|
|
|
|
func assertSameSet(t *testing.T, what string, goSide, tsSide []string) {
|
|
t.Helper()
|
|
if !reflect.DeepEqual(sorted(goSide), sorted(tsSide)) {
|
|
t.Errorf("%s differ:\n Go: %v\n TS: %v", what, sorted(goSide), sorted(tsSide))
|
|
}
|
|
}
|
|
|
|
// The Go catalogs and the frontend contract files describe the same contract.
|
|
func TestContractCatalogsMatchFrontend(t *testing.T) {
|
|
ui := readFrontendContract(t, "styles/ui-contract.ts")
|
|
if got := tsVersion(t, ui, "UI_API_VERSION"); got != UIAPIVersion {
|
|
t.Errorf("UI_API_VERSION = %s, Go UIAPIVersion = %s", got, UIAPIVersion)
|
|
}
|
|
var stableSlots, expSlots []string
|
|
for id, spec := range UISlotCatalog {
|
|
if spec.Status == ContractStable {
|
|
stableSlots = append(stableSlots, id)
|
|
} else {
|
|
expSlots = append(expSlots, id)
|
|
}
|
|
}
|
|
assertSameSet(t, "stable slots", stableSlots, tsArray(t, ui, "UI_CONTRACT_SLOTS"))
|
|
assertSameSet(t, "experimental slots", expSlots, tsArray(t, ui, "UI_CONTRACT_SLOTS_EXPERIMENTAL"))
|
|
|
|
var stableLayers, expLayers []string
|
|
for id, st := range UILayerCatalog {
|
|
if st == ContractStable {
|
|
stableLayers = append(stableLayers, id)
|
|
} else {
|
|
expLayers = append(expLayers, id)
|
|
}
|
|
}
|
|
assertSameSet(t, "stable layers", stableLayers, tsArray(t, ui, "UI_CONTRACT_LAYERS"))
|
|
assertSameSet(t, "experimental layers", expLayers, tsArray(t, ui, "UI_CONTRACT_LAYERS_EXPERIMENTAL"))
|
|
|
|
var layout []string
|
|
for opt, vals := range ThemeLayoutCatalog {
|
|
for _, v := range vals {
|
|
layout = append(layout, opt+"="+v)
|
|
}
|
|
}
|
|
assertSameSet(t, "layout options", layout, tsArray(t, ui, "UI_CONTRACT_LAYOUT_OPTIONS"))
|
|
assertSameSet(t, "icon names", ThemeIconNames, tsArray(t, ui, "UI_CONTRACT_ICONS"))
|
|
|
|
var locations, expLocations []string
|
|
for loc, spec := range ViewLocationCatalog {
|
|
if spec.Status == ContractStable {
|
|
locations = append(locations, loc)
|
|
} else {
|
|
expLocations = append(expLocations, loc)
|
|
}
|
|
}
|
|
assertSameSet(t, "stable view locations", locations, tsArray(t, ui, "UI_CONTRACT_VIEW_LOCATIONS"))
|
|
assertSameSet(t, "experimental view locations", expLocations, tsArray(t, ui, "UI_CONTRACT_VIEW_LOCATIONS_EXPERIMENTAL"))
|
|
|
|
bridge := readFrontendContract(t, "lib/bridgeContract.ts")
|
|
if got := tsVersion(t, bridge, "BRIDGE_API_VERSION"); got != BridgeAPIVersion {
|
|
t.Errorf("BRIDGE_API_VERSION = %s, Go BridgeAPIVersion = %s", got, BridgeAPIVersion)
|
|
}
|
|
var stableMethods, expMethods []string
|
|
for m, spec := range BridgeMethodCatalog {
|
|
if spec.Status == ContractStable {
|
|
stableMethods = append(stableMethods, m)
|
|
} else {
|
|
expMethods = append(expMethods, m)
|
|
}
|
|
}
|
|
assertSameSet(t, "stable bridge methods", stableMethods, tsArray(t, bridge, "BRIDGE_METHODS"))
|
|
assertSameSet(t, "experimental bridge methods", expMethods, tsArray(t, bridge, "BRIDGE_METHODS_EXPERIMENTAL"))
|
|
var stableEvents, expEvents []string
|
|
for ev, st := range BridgeEventCatalog {
|
|
if st == ContractStable {
|
|
stableEvents = append(stableEvents, ev)
|
|
} else {
|
|
expEvents = append(expEvents, ev)
|
|
}
|
|
}
|
|
assertSameSet(t, "stable bridge events", stableEvents, tsArray(t, bridge, "BRIDGE_EVENTS"))
|
|
assertSameSet(t, "experimental bridge events", expEvents, tsArray(t, bridge, "BRIDGE_EVENTS_EXPERIMENTAL"))
|
|
}
|
|
|
|
// A new contributes field must be added to ContributionCatalog with a status.
|
|
func TestContributionCatalogCoversManifest(t *testing.T) {
|
|
ty := reflect.TypeOf(Contributes{})
|
|
var fields []string
|
|
for i := 0; i < ty.NumField(); i++ {
|
|
name, _, _ := strings.Cut(ty.Field(i).Tag.Get("json"), ",")
|
|
fields = append(fields, name)
|
|
}
|
|
var catalog []string
|
|
for k := range ContributionCatalog {
|
|
catalog = append(catalog, k)
|
|
}
|
|
assertSameSet(t, "contributes fields", fields, catalog)
|
|
}
|
|
|
|
func TestHostFeaturesAreStableOnly(t *testing.T) {
|
|
features := HostFeatures()
|
|
if !sort.StringsAreSorted(features) {
|
|
t.Fatal("HostFeatures must be sorted")
|
|
}
|
|
has := map[string]bool{}
|
|
for _, f := range features {
|
|
has[f] = true
|
|
}
|
|
for _, want := range []string{"bridge.hello", "bridge.vm.list", "bridge.file.pick", "contrib.views", "contrib.autoInstallers", "view.sidebar", "event.theme.changed", "event.vm.stateChanged", "event.task.updated", "event.view.visibilityChanged", "event.vm.phaseChanged", "host.ui.confirm", "host.session", "host.console.screenshot.region", "host.vm.finishInstall", "host.vm.restart", "host.vm.telemetry", "slot.sidebar.footer", "slot.settings.plugin.panel", "slot.vm.toolbar.menu", "contrib.themes", "contrib.imageSources", "slot.vm.toolbar", "slot.nav.item.trailing", "layer.overlay", "layer.background", "theme.icons", "theme.layout", "theme.brandMark"} {
|
|
if !has[want] {
|
|
t.Errorf("missing stable feature %s", want)
|
|
}
|
|
}
|
|
for _, unwanted := range []string{"slot.sidebar.footer.panel", "slot.vm.card.vmCard", "contrib.statusItems"} {
|
|
if has[unwanted] {
|
|
t.Errorf("experimental entry %s advertised as a feature", unwanted)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestResolveBridgeMethodAliases(t *testing.T) {
|
|
if name, spec, ok := ResolveBridgeMethod("notify"); !ok || name != "ui.notify" || spec.Status != ContractStable {
|
|
t.Fatalf("notify alias = %q %+v %v", name, spec, ok)
|
|
}
|
|
if _, spec, ok := ResolveBridgeMethod("file.pick"); !ok || spec.Status != ContractStable || spec.Permission != "fs:pick" {
|
|
t.Fatalf("file.pick = %+v %v", spec, ok)
|
|
}
|
|
if _, _, ok := ResolveBridgeMethod("fs.readAny"); ok {
|
|
t.Fatal("unknown bridge method resolved")
|
|
}
|
|
}
|
|
|
|
func uiManifest() Manifest {
|
|
return Manifest{Schema: 1, ID: "vendor.ui", Version: "1.0.0", Name: LocalizedText{EnUS: "UI"},
|
|
Entry: Entry{PanelDir: "ui"}, Permissions: []string{"ui:slot"}}
|
|
}
|
|
|
|
func TestValidateUIContract(t *testing.T) {
|
|
view := func(id, loc string) ViewContribution {
|
|
return ViewContribution{ID: id, Title: LocalizedText{EnUS: id}, Location: loc, Entry: "index.html"}
|
|
}
|
|
cases := []struct {
|
|
name string
|
|
mutate func(*Manifest)
|
|
wantErr string
|
|
}{
|
|
{"sidebar view", func(m *Manifest) { m.Contributes.Views = []ViewContribution{view("console", "sidebar")} }, ""},
|
|
{"unknown location", func(m *Manifest) { m.Contributes.Views = []ViewContribution{view("x", "titlebar")} }, "unknown location"},
|
|
{"too many sidebar views", func(m *Manifest) {
|
|
m.Contributes.Views = []ViewContribution{view("a", "sidebar"), view("b", "sidebar"), view("c", "sidebar")}
|
|
}, "too many views"},
|
|
{"duplicate view", func(m *Manifest) {
|
|
m.Contributes.Views = []ViewContribution{view("a", "vm.tab"), view("a", "dialog")}
|
|
}, "duplicate view"},
|
|
{"view without panelDir", func(m *Manifest) {
|
|
m.Entry.PanelDir = ""
|
|
m.Contributes.Views = []ViewContribution{view("a", "dialog")}
|
|
}, "requires entry.panelDir"},
|
|
{"view escaping entry", func(m *Manifest) {
|
|
v := view("a", "dialog")
|
|
v.Entry = "../secret.html"
|
|
m.Contributes.Views = []ViewContribution{v}
|
|
}, "invalid view"},
|
|
{"panel in unknown slot", func(m *Manifest) {
|
|
m.Contributes.Panels = []PanelContribution{{ID: "p", Slot: "titlebar.left", Entry: "p.html"}}
|
|
}, "unknown slot"},
|
|
{"panel in slot without panels", func(m *Manifest) {
|
|
m.Contributes.Panels = []PanelContribution{{ID: "p", Slot: "vm.preview.tl", Entry: "p.html"}}
|
|
}, "does not accept panel"},
|
|
{"menu outside toolbar", func(m *Manifest) {
|
|
m.Contributes.Menus = []MenuContribution{{ID: "m", Slot: "empty.state", Command: "c"}}
|
|
}, "does not accept menu"},
|
|
{"layout value", func(m *Manifest) {
|
|
m.Contributes.Themes = []ThemeContribution{{ID: "t", Name: LocalizedText{EnUS: "t"}, Layout: &ThemeLayout{SidebarMode: "hidden"}}}
|
|
}, "layout.sidebarMode"},
|
|
{"unknown icon", func(m *Manifest) {
|
|
m.Contributes.Themes = []ThemeContribution{{ID: "t", Name: LocalizedText{EnUS: "t"}, Icons: map[string]string{"rocket": "r.svg"}}}
|
|
}, "unknown icon"},
|
|
{"bridgeApi range", func(m *Manifest) { m.Engines.BridgeAPI = "^2.0.0" }, "incompatible bridgeApi"},
|
|
{"decoration in layer", func(m *Manifest) {
|
|
m.Contributes.Themes = []ThemeContribution{{ID: "t", Name: LocalizedText{EnUS: "t"},
|
|
Decorations: []ThemeDecoration{{ID: "sky", Slot: "layer.background"}, {ID: "pet", Slot: "nav.item.trailing"}}}}
|
|
}, ""},
|
|
{"decoration in unknown slot", func(m *Manifest) {
|
|
m.Contributes.Themes = []ThemeContribution{{ID: "t", Name: LocalizedText{EnUS: "t"},
|
|
Decorations: []ThemeDecoration{{ID: "x", Slot: "sidebar.middle"}}}}
|
|
}, "unknown slot or layer"},
|
|
{"valid image source", func(m *Manifest) {
|
|
m.Contributes.ImageSources = []ImageSourceContribution{{ID: "linux", Title: LocalizedText{EnUS: "Linux"}, Entry: "images.html"}}
|
|
}, ""},
|
|
{"image source without panelDir", func(m *Manifest) {
|
|
m.Entry.PanelDir = ""
|
|
m.Contributes.ImageSources = []ImageSourceContribution{{ID: "linux", Title: LocalizedText{EnUS: "Linux"}, Entry: "images.html"}}
|
|
}, "requires entry.panelDir"},
|
|
{"image source missing title", func(m *Manifest) {
|
|
m.Contributes.ImageSources = []ImageSourceContribution{{ID: "linux", Entry: "images.html"}}
|
|
}, "missing a localized title"},
|
|
{"image source escaping entry", func(m *Manifest) {
|
|
m.Contributes.ImageSources = []ImageSourceContribution{{ID: "linux", Title: LocalizedText{EnUS: "Linux"}, Entry: "../escape.html"}}
|
|
}, "invalid image source"},
|
|
{"valid autoInstaller", func(m *Manifest) {
|
|
m.Entry.Sidecar = "bin/auto.exe"
|
|
m.Contributes.AutoInstallers = []AutoInstallerContribution{{ID: "macos-local", Title: LocalizedText{EnUS: "macOS Auto-Install"}, GuestFamilies: []string{"macos"}}}
|
|
}, ""},
|
|
{"autoInstaller without sidecar", func(m *Manifest) {
|
|
m.Contributes.AutoInstallers = []AutoInstallerContribution{{ID: "macos-local", Title: LocalizedText{EnUS: "macOS Auto-Install"}, GuestFamilies: []string{"macos"}}}
|
|
}, "requires entry.sidecar"},
|
|
{"autoInstaller unknown family", func(m *Manifest) {
|
|
m.Entry.Sidecar = "bin/auto.exe"
|
|
m.Contributes.AutoInstallers = []AutoInstallerContribution{{ID: "bsd", Title: LocalizedText{EnUS: "BSD"}, GuestFamilies: []string{"bsd"}}}
|
|
}, "unknown guest family"},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
m := uiManifest()
|
|
tc.mutate(&m)
|
|
err := validateUIContract(m)
|
|
if tc.wantErr == "" && err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
if tc.wantErr != "" && (err == nil || !strings.Contains(err.Error(), tc.wantErr)) {
|
|
t.Fatalf("err = %v, want %q", err, tc.wantErr)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestContractFindings(t *testing.T) {
|
|
m := uiManifest()
|
|
m.Contributes.Views = []ViewContribution{{ID: "console", Title: LocalizedText{EnUS: "c"}, Location: "sidebar", Entry: "index.html"}}
|
|
m.Contributes.Panels = []PanelContribution{{ID: "card", Slot: "vm.card", Entry: "card.html"}, {ID: "s", Slot: "settings.plugin", Entry: "s.html"}}
|
|
m.Contributes.Themes = []ThemeContribution{{ID: "t", Name: LocalizedText{EnUS: "t"}, Layout: &ThemeLayout{Density: "compact"}}}
|
|
raw := []byte(`{"schema":1,"id":"vendor.ui","version":"1.0.0","name":{"en-US":"UI"},"futureField":true}`)
|
|
|
|
checks := map[string][]string{}
|
|
for _, f := range ContractFindings(m, raw) {
|
|
if f.Severity != ScanSeverityPending {
|
|
t.Errorf("finding %+v must be non-blocking", f)
|
|
}
|
|
checks[f.Check] = append(checks[f.Check], f.Target)
|
|
}
|
|
exp := strings.Join(checks["contract-experimental"], " ")
|
|
for _, want := range []string{"panel:card"} {
|
|
if !strings.Contains(exp, want) {
|
|
t.Errorf("experimental findings %q miss %s", exp, want)
|
|
}
|
|
}
|
|
if strings.Contains(exp, "panel:s") {
|
|
t.Error("settings.plugin panels are stable and must not be reported")
|
|
}
|
|
if strings.Contains(exp, "contributes.views") {
|
|
t.Error("implemented views are stable and must not be reported")
|
|
}
|
|
if len(checks["contract-unknown-field"]) != 1 {
|
|
t.Errorf("unknown field findings = %v", checks["contract-unknown-field"])
|
|
}
|
|
if engines := strings.Join(checks["contract-engines"], " "); !strings.Contains(engines, "engines.uiApi") || !strings.Contains(engines, "engines.bridgeApi") {
|
|
t.Errorf("engines findings = %q", engines)
|
|
}
|
|
|
|
m.Engines = Engines{UIAPI: "^2.0.0", BridgeAPI: "^1.0.0"}
|
|
m.Contributes = Contributes{Panels: []PanelContribution{{ID: "s", Slot: "settings.plugin", Entry: "s.html"}}}
|
|
if got := ContractFindings(m, []byte(`{"schema":1,"id":"vendor.ui"}`)); len(got) != 0 {
|
|
t.Fatalf("a manifest using only stable entries got findings: %+v", got)
|
|
}
|
|
}
|