feat(plugin): add host download service with origin, redirect and close guards (A3)
This commit is contained in:
1 parent
ea9b6c7b56
commit
6fb156b3ae
20 files changed
+984
-5
No files matched your search
+16
-1
@@ -97,6 +97,7 @@ export const App: React.FC = () => {
|
||||
const [affinityVersion, setAffinityVersion] = useState(0)
|
||||
const [deleteTarget, setDeleteTarget] = useState<string | null>(null)
|
||||
const [discardSuspendTarget, setDiscardSuspendTarget] = useState<string | null>(null)
|
||||
const [closeDownloadsOpen, setCloseDownloadsOpen] = useState(false)
|
||||
const [cloneSource, setCloneSource] = useState<{ name: string; driverID: string } | null>(null)
|
||||
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
|
||||
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
|
||||
@@ -1041,7 +1042,7 @@ export const App: React.FC = () => {
|
||||
// Global shortcuts (see docs/design-guidelines.md). Dialogs own the keyboard while open.
|
||||
const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {})
|
||||
const appDialogOpen = showSetup || showReadOnly || showWizard || showSettings || affinityTarget || deleteTarget ||
|
||||
discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate
|
||||
discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate || closeDownloadsOpen
|
||||
shortcutRef.current = (e: KeyboardEvent) => {
|
||||
if (!e.ctrlKey || e.altKey || e.metaKey) return
|
||||
if (appDialogOpen) return
|
||||
@@ -1073,6 +1074,9 @@ export const App: React.FC = () => {
|
||||
return () => { offSelect(); offNew(); offDiscard() }
|
||||
}, [])
|
||||
|
||||
// Closing the window while a download runs asks first (beforeClose in Go).
|
||||
useEffect(() => events.onConfirmCloseDownloads(() => setCloseDownloadsOpen(true)), [])
|
||||
|
||||
// Native Wails file drag-and-drop delivery into the selected VM's shared folder.
|
||||
const dropTargetRef = useRef<{ name: string; ready: boolean }>({ name: '', ready: false })
|
||||
dropTargetRef.current = {
|
||||
@@ -1513,6 +1517,17 @@ export const App: React.FC = () => {
|
||||
<DeleteDialog locale={locale} name={findVM(deleteTarget)?.name ?? deleteTarget} onCancel={() => setDeleteTarget(null)} onConfirm={confirmDelete} />
|
||||
)}
|
||||
|
||||
{closeDownloadsOpen && (
|
||||
<ConfirmDialog
|
||||
title={tr('closeDownloadsTitle')}
|
||||
description={tr('closeDownloadsDesc')}
|
||||
cancelLabel={tr('cancel')}
|
||||
confirmLabel={tr('closeDownloadsConfirm')}
|
||||
onCancel={() => setCloseDownloadsOpen(false)}
|
||||
onConfirm={() => { setCloseDownloadsOpen(false); void api.QuitApp() }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{discardSuspendTarget && (() => {
|
||||
const targetVM = findVM(discardSuspendTarget)
|
||||
const targetName = targetVM?.name ?? discardSuspendTarget
|
||||
|
||||
@@ -10,6 +10,9 @@ export const coreZh: Record<string, string> = {
|
||||
"cancelQueue": "取消排队",
|
||||
"clear": "清空",
|
||||
"close": "关闭",
|
||||
"closeDownloadsConfirm": "退出",
|
||||
"closeDownloadsDesc": "仍有下载正在进行,退出会中断它们。",
|
||||
"closeDownloadsTitle": "退出 Reims-Go?",
|
||||
"closeWindow": "关闭",
|
||||
"collapseLogs": "收起日志",
|
||||
"copy": "复制",
|
||||
@@ -148,6 +151,7 @@ export const coreZh: Record<string, string> = {
|
||||
"taskAppUpdate": "下载 Reims-Go {v}",
|
||||
"taskCreate": "创建 {name}",
|
||||
"taskDownload": "下载 macOS {v}",
|
||||
"taskPluginDownload": "下载 {name}",
|
||||
"taskRecoveryDownload": "正在为 {name} 拉取并挂载在线恢复镜像",
|
||||
"taskRuntime": "安装运行时 {v}",
|
||||
"tasksRunning": "{n, plural, other {# 个任务进行中}}",
|
||||
@@ -204,6 +208,9 @@ export const coreEn: Record<string, string> = {
|
||||
"cancelQueue": "Cancel queued download",
|
||||
"clear": "Clear",
|
||||
"close": "Close",
|
||||
"closeDownloadsConfirm": "Quit",
|
||||
"closeDownloadsDesc": "Downloads are still running. Quitting stops them.",
|
||||
"closeDownloadsTitle": "Quit Reims-Go?",
|
||||
"closeWindow": "Close",
|
||||
"collapseLogs": "Hide logs",
|
||||
"copy": "Copy",
|
||||
@@ -342,6 +349,7 @@ export const coreEn: Record<string, string> = {
|
||||
"taskAppUpdate": "Downloading Reims-Go {v}",
|
||||
"taskCreate": "Creating {name}",
|
||||
"taskDownload": "Downloading macOS {v}",
|
||||
"taskPluginDownload": "Downloading {name}",
|
||||
"taskRecoveryDownload": "Downloading online recovery for {name}",
|
||||
"taskRuntime": "Installing runtime {v}",
|
||||
"tasksRunning": "{n, plural, one {# task running} other {# tasks running}}",
|
||||
|
||||
@@ -135,6 +135,9 @@ export type I18nKey =
|
||||
| "cloneTitle"
|
||||
| "cloneVM"
|
||||
| "close"
|
||||
| "closeDownloadsConfirm"
|
||||
| "closeDownloadsDesc"
|
||||
| "closeDownloadsTitle"
|
||||
| "closeWindow"
|
||||
| "collapseLogs"
|
||||
| "commandToggle"
|
||||
@@ -1049,6 +1052,7 @@ export type I18nKey =
|
||||
| "taskAppUpdate"
|
||||
| "taskCreate"
|
||||
| "taskDownload"
|
||||
| "taskPluginDownload"
|
||||
| "taskRecoveryDownload"
|
||||
| "taskRuntime"
|
||||
| "tasksRunning"
|
||||
|
||||
@@ -41,6 +41,7 @@ export function taskTitle(locale: Locale, task: Task): string {
|
||||
case 'vm-create': return t(locale, 'taskCreate', { name: task.subject })
|
||||
case 'runtime-install': return t(locale, 'taskRuntime', { v: task.subject })
|
||||
case 'app-update': return t(locale, 'taskAppUpdate', { v: task.subject })
|
||||
case 'plugin-download': return t(locale, 'taskPluginDownload', { name: task.subject })
|
||||
default: return task.subject
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,6 +196,8 @@ export const events = {
|
||||
onTraySelectVM: (cb: (name: string) => void) => eventsOn('reims:tray-select-vm', cb),
|
||||
onTrayNewVM: (cb: () => void) => eventsOn('reims:tray-new-vm', cb),
|
||||
onTrayDiscardSuspend: (cb: (name: string) => void) => eventsOn('reims:tray-discard-suspend', cb),
|
||||
// Closing the window while a download runs (internal/app/app.go beforeClose).
|
||||
onConfirmCloseDownloads: (cb: () => void) => eventsOn('reims:confirm-close-downloads', cb),
|
||||
// Renderer health watchdog & crash reporting (internal/app/ui_health.go).
|
||||
onUIPing: (cb: () => void) => eventsOn('reims:ui-ping', cb),
|
||||
emitUIPong: () => eventsEmit('reims:ui-pong'),
|
||||
|
||||
@@ -258,6 +258,12 @@ func (a *App) beforeClose(ctx context.Context) bool {
|
||||
wailsRuntime.WindowHide(ctx)
|
||||
return true
|
||||
}
|
||||
if tasks.hasRunningDownload() {
|
||||
// Closing now would abort a download: ask first. The window's
|
||||
// confirmation calls QuitApp, which lets the next close through.
|
||||
wailsRuntime.EventsEmit(ctx, "reims:confirm-close-downloads", true)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,409 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/fetch"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/netproxy"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
const (
|
||||
taskKindPluginDownload = "plugin-download"
|
||||
downloadMaxBytes = int64(64) << 30
|
||||
downloadMaxRedirects = 10
|
||||
downloadStall = 60 * time.Second
|
||||
)
|
||||
|
||||
// pluginDownload is one download a plugin started through the host.
|
||||
type pluginDownload struct {
|
||||
pluginID string
|
||||
taskID string
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
var pluginDownloads = struct {
|
||||
mu sync.Mutex
|
||||
seq int
|
||||
m map[string]*pluginDownload
|
||||
}{m: map[string]*pluginDownload{}}
|
||||
|
||||
type downloadNotifier func(method string, params any)
|
||||
|
||||
func (a *App) downloadHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
|
||||
if mgr == nil || mgr.Broker() == nil {
|
||||
return nil
|
||||
}
|
||||
broker := mgr.Broker()
|
||||
return map[string]plugin.RPCRequestHandler{
|
||||
"host/download.start": func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
a.mu.Lock()
|
||||
dataRoot := ""
|
||||
if a.cfg != nil {
|
||||
dataRoot = a.cfg.DataRoot
|
||||
}
|
||||
a.mu.Unlock()
|
||||
roots := downloadRoots(mgr, pluginID, dataRoot)
|
||||
notify := func(method string, params any) { mgr.NotifySidecar(pluginID, method, params) }
|
||||
res, err := a.startPluginDownload(broker, notify, pluginID, roots, raw)
|
||||
if err != nil {
|
||||
broker.Audit(pluginID, "HOST_API_ERROR", "host/download.start")
|
||||
return nil, err
|
||||
}
|
||||
broker.Audit(pluginID, "HOST_API", "host/download.start")
|
||||
return res, nil
|
||||
},
|
||||
"host/download.cancel": func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
res, err := cancelPluginDownload(pluginID, raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
broker.Audit(pluginID, "HOST_API", "host/download.cancel")
|
||||
return res, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// downloadRoots lists where a plugin's downloads may land: its own data
|
||||
// folder first, then the VM roots its drivers declared.
|
||||
func downloadRoots(mgr *plugin.Manager, pluginID, dataRoot string) []string {
|
||||
roots := []string{mgr.Layout().DataDir(pluginID)}
|
||||
reg := mgr.Registry()
|
||||
owned := map[string]bool{}
|
||||
for _, id := range reg.DeclaredDriverIDs(pluginID) {
|
||||
owned[id] = true
|
||||
}
|
||||
for driverID, rels := range reg.DeclaredVMRoots() {
|
||||
if !owned[driverID] || dataRoot == "" {
|
||||
continue
|
||||
}
|
||||
for _, rel := range rels {
|
||||
roots = append(roots, filepath.Join(dataRoot, filepath.FromSlash(rel)))
|
||||
}
|
||||
}
|
||||
return roots
|
||||
}
|
||||
|
||||
func isHex64(s string) bool {
|
||||
if len(s) != 64 {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'f' || r >= 'A' && r <= 'F') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// rejectInternalHost fails for hosts that resolve to this machine or a
|
||||
// private network, so a redirect cannot reach services behind the firewall.
|
||||
func rejectInternalHost(host string) error {
|
||||
check := func(ip net.IP) error {
|
||||
if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsUnspecified() || ip.IsMulticast() {
|
||||
return fmt.Errorf("redirect to the internal address %s is not allowed", ip)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
return check(ip)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
ips, err := net.DefaultResolver.LookupIPAddr(ctx, host)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve redirect host %q: %w", host, err)
|
||||
}
|
||||
for _, ip := range ips {
|
||||
if err := check(ip.IP); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// safeDownloadClient follows at most ten redirects, never from HTTPS to plain
|
||||
// HTTP, and, unless the first URL was loopback itself, never to an internal
|
||||
// address.
|
||||
func safeDownloadClient(initial string) *http.Client {
|
||||
client := netproxy.NewClient()
|
||||
allowInternal := false
|
||||
if u, err := parseURLHost(initial); err == nil {
|
||||
allowInternal = plugin.IsLoopbackHost(u)
|
||||
}
|
||||
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= downloadMaxRedirects {
|
||||
return errors.New("too many redirects")
|
||||
}
|
||||
if req.URL.User != nil {
|
||||
return errors.New("redirect with user info is not allowed")
|
||||
}
|
||||
if req.URL.Scheme != "https" && req.URL.Scheme != "http" {
|
||||
return fmt.Errorf("redirect to scheme %q is not allowed", req.URL.Scheme)
|
||||
}
|
||||
if prev := via[len(via)-1]; prev.URL.Scheme == "https" && req.URL.Scheme != "https" {
|
||||
return errors.New("redirect from HTTPS to plain HTTP is not allowed")
|
||||
}
|
||||
if !allowInternal {
|
||||
if err := rejectInternalHost(req.URL.Hostname()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
func parseURLHost(raw string) (string, error) {
|
||||
req, err := http.NewRequest(http.MethodGet, raw, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return req.URL.Hostname(), nil
|
||||
}
|
||||
|
||||
// resolveExpectedSum reads a SHA-256 from a checksum document: a sums file
|
||||
// with "<hex> <name>" lines (name selects the line) or a file holding one hash.
|
||||
func resolveExpectedSum(ctx context.Context, client *http.Client, sumsURL, name string) (string, error) {
|
||||
req, err := fetch.NewRequest(ctx, sumsURL)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("download checksum: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("download checksum: HTTP %d", resp.StatusCode)
|
||||
}
|
||||
sc := bufio.NewScanner(io.LimitReader(resp.Body, 1<<20))
|
||||
for sc.Scan() {
|
||||
fields := strings.Fields(sc.Text())
|
||||
if len(fields) == 0 || !isHex64(fields[0]) {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case len(fields) == 1 && name == "":
|
||||
return strings.ToLower(fields[0]), nil
|
||||
case len(fields) >= 2 && strings.TrimPrefix(fields[1], "*") == name:
|
||||
return strings.ToLower(fields[0]), nil
|
||||
}
|
||||
}
|
||||
if name == "" {
|
||||
return "", errors.New("the checksum document holds no SHA-256")
|
||||
}
|
||||
return "", fmt.Errorf("the checksum document has no entry for %s", name)
|
||||
}
|
||||
|
||||
type progressWriter struct {
|
||||
w io.Writer
|
||||
done int64
|
||||
total int64
|
||||
fn func(done, total int64)
|
||||
}
|
||||
|
||||
func (p *progressWriter) Write(b []byte) (int, error) {
|
||||
n, err := p.w.Write(b)
|
||||
p.done += int64(n)
|
||||
if p.fn != nil {
|
||||
p.fn(p.done, p.total)
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
// downloadPlain fetches url to dest with no checksum: into dest.part, then renamed.
|
||||
func downloadPlain(ctx context.Context, client *http.Client, url, dest string, size int64, fn func(done, total int64)) error {
|
||||
req, err := fetch.NewRequest(ctx, url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("download: HTTP %d", resp.StatusCode)
|
||||
}
|
||||
total := size
|
||||
if total <= 0 && resp.ContentLength > 0 {
|
||||
total = resp.ContentLength
|
||||
}
|
||||
if total > downloadMaxBytes {
|
||||
return fmt.Errorf("download is larger than %d bytes", downloadMaxBytes)
|
||||
}
|
||||
part := dest + ".part"
|
||||
f, err := os.OpenFile(part, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := io.Copy(&progressWriter{w: f, total: total, fn: fn}, io.LimitReader(resp.Body, downloadMaxBytes+1))
|
||||
closeErr := f.Close()
|
||||
if err == nil && n > downloadMaxBytes {
|
||||
err = fmt.Errorf("download is larger than %d bytes", downloadMaxBytes)
|
||||
}
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err == nil {
|
||||
err = ctx.Err()
|
||||
}
|
||||
if err != nil {
|
||||
_ = os.Remove(part)
|
||||
return err
|
||||
}
|
||||
return os.Rename(part, dest)
|
||||
}
|
||||
|
||||
type downloadEvent struct {
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"` // running | done | failed | canceled
|
||||
Done int64 `json:"done"`
|
||||
Total int64 `json:"total"`
|
||||
Percent float64 `json:"percent"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// startPluginDownload validates a download request and runs it in the
|
||||
// background as a task. It returns the download ID at once.
|
||||
func (a *App) startPluginDownload(broker *plugin.Broker, notify downloadNotifier, pluginID string, roots []string, raw json.RawMessage) (any, error) {
|
||||
var req struct {
|
||||
URL string `json:"url"`
|
||||
SHA256 string `json:"sha256"`
|
||||
SHA256URL string `json:"sha256_url"`
|
||||
SHA256Name string `json:"sha256_name"`
|
||||
Dest string `json:"dest"`
|
||||
Size int64 `json:"size"`
|
||||
Label string `json:"label"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := broker.AuthorizeNetOrigin(pluginID, req.URL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(req.SHA256URL) != "" {
|
||||
if err := broker.AuthorizeNetOrigin(pluginID, req.SHA256URL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
want := strings.ToLower(strings.TrimSpace(req.SHA256))
|
||||
if want != "" && !isHex64(want) {
|
||||
return nil, errors.New("sha256 must be 64 hex digits")
|
||||
}
|
||||
if len(roots) == 0 {
|
||||
return nil, errors.New("this plugin has no folder it may download into")
|
||||
}
|
||||
dest := strings.TrimSpace(req.Dest)
|
||||
if dest == "" {
|
||||
return nil, errors.New("dest is required")
|
||||
}
|
||||
if !filepath.IsAbs(dest) {
|
||||
dest = filepath.Join(roots[0], dest)
|
||||
}
|
||||
dest = filepath.Clean(dest)
|
||||
if !pathInsideAny(dest, roots...) {
|
||||
return nil, errors.New("dest must stay inside the plugin's data folder or a VM root its driver declared")
|
||||
}
|
||||
if st, err := os.Lstat(dest); err == nil && (st.Mode()&os.ModeSymlink != 0 || st.IsDir()) {
|
||||
return nil, errors.New("dest must be a plain file path")
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !pathInsideAny(dest, roots...) {
|
||||
return nil, errors.New("dest must stay inside the plugin's data folder or a VM root its driver declared")
|
||||
}
|
||||
|
||||
a.ensureTaskEmitter()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
label := strings.TrimSpace(req.Label)
|
||||
if label == "" {
|
||||
label = filepath.Base(dest)
|
||||
}
|
||||
taskID := tasks.start(taskKindPluginDownload, label, "", cancel)
|
||||
pluginDownloads.mu.Lock()
|
||||
pluginDownloads.seq++
|
||||
id := fmt.Sprintf("download-%d", pluginDownloads.seq)
|
||||
pluginDownloads.m[id] = &pluginDownload{pluginID: pluginID, taskID: taskID, cancel: cancel}
|
||||
pluginDownloads.mu.Unlock()
|
||||
|
||||
go func() {
|
||||
client := safeDownloadClient(req.URL)
|
||||
var lastNotify atomic.Int64
|
||||
progress := func(done, total int64) {
|
||||
percent := -1.0
|
||||
if total > 0 {
|
||||
percent = float64(done) * 100 / float64(total)
|
||||
}
|
||||
tasks.update(taskID, host.Update{Kind: host.KindProgress, Done: done, Total: total, Percent: percent})
|
||||
now := time.Now().UnixMilli()
|
||||
if prev := lastNotify.Load(); now-prev >= 250 && lastNotify.CompareAndSwap(prev, now) {
|
||||
notify("download/progress", downloadEvent{ID: id, Status: "running", Done: done, Total: total, Percent: percent})
|
||||
}
|
||||
}
|
||||
var err error
|
||||
if want == "" && strings.TrimSpace(req.SHA256URL) != "" {
|
||||
name := req.SHA256Name
|
||||
want, err = resolveExpectedSum(ctx, client, req.SHA256URL, name)
|
||||
}
|
||||
if err == nil {
|
||||
if want != "" {
|
||||
_, err = fetch.ResumeDirect(ctx, client, req.URL, dest, req.Size, want, progress,
|
||||
fetch.ResumeOptions{MaxBytes: downloadMaxBytes, StallTimeout: downloadStall})
|
||||
} else {
|
||||
err = downloadPlain(ctx, client, req.URL, dest, req.Size, progress)
|
||||
}
|
||||
}
|
||||
pluginDownloads.mu.Lock()
|
||||
delete(pluginDownloads.m, id)
|
||||
pluginDownloads.mu.Unlock()
|
||||
cancel()
|
||||
ev := downloadEvent{ID: id, Status: "done", Path: dest, Percent: 100}
|
||||
switch {
|
||||
case err == nil:
|
||||
case errors.Is(err, context.Canceled) || strings.Contains(err.Error(), context.Canceled.Error()):
|
||||
ev = downloadEvent{ID: id, Status: "canceled"}
|
||||
default:
|
||||
ev = downloadEvent{ID: id, Status: "failed", Error: host.RedactText(err.Error())}
|
||||
}
|
||||
tasks.finish(taskID, dest, err)
|
||||
notify("download/progress", ev)
|
||||
broker.Audit(pluginID, "DOWNLOAD_"+strings.ToUpper(ev.Status), id)
|
||||
}()
|
||||
return map[string]any{"id": id, "task_id": taskID}, nil
|
||||
}
|
||||
|
||||
// cancelPluginDownload stops one of pluginID's own downloads.
|
||||
func cancelPluginDownload(pluginID string, raw json.RawMessage) (any, error) {
|
||||
var req struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pluginDownloads.mu.Lock()
|
||||
d := pluginDownloads.m[req.ID]
|
||||
pluginDownloads.mu.Unlock()
|
||||
if d == nil || d.pluginID != pluginID {
|
||||
return nil, fmt.Errorf("no download %q of this plugin is running", req.ID)
|
||||
}
|
||||
d.cancel()
|
||||
return map[string]any{"ok": true}, nil
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/testutil/fakedriver"
|
||||
)
|
||||
|
||||
type downloadTestEnv struct {
|
||||
app *App
|
||||
h *fakedriver.Harness
|
||||
plugin string
|
||||
other string
|
||||
roots []string
|
||||
mu sync.Mutex
|
||||
events []downloadEvent
|
||||
}
|
||||
|
||||
func newDownloadTestEnv(t *testing.T, origins ...string) *downloadTestEnv {
|
||||
t.Helper()
|
||||
h := fakedriver.NewHarness(t)
|
||||
e := &downloadTestEnv{h: h, plugin: "test.fake.dl", other: "test.fake.other"}
|
||||
perms := make([]string, 0, len(origins))
|
||||
for _, o := range origins {
|
||||
perms = append(perms, "net:"+o)
|
||||
}
|
||||
h.AddWithPermissions("hosted", e.plugin, "test.driver.dl", perms...)
|
||||
h.Add("hosted", e.other, "test.driver.dlother")
|
||||
e.app = &App{cfg: &config.Config{DataRoot: h.DataRoot}}
|
||||
e.roots = []string{filepath.Join(h.DataRoot, "plugins", "data", e.plugin)}
|
||||
return e
|
||||
}
|
||||
|
||||
func (e *downloadTestEnv) notify(method string, params any) {
|
||||
if method != "download/progress" {
|
||||
return
|
||||
}
|
||||
ev, ok := params.(downloadEvent)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
e.mu.Lock()
|
||||
e.events = append(e.events, ev)
|
||||
e.mu.Unlock()
|
||||
}
|
||||
|
||||
func (e *downloadTestEnv) start(t *testing.T, pluginID string, req map[string]any) (string, error) {
|
||||
t.Helper()
|
||||
raw, _ := json.Marshal(req)
|
||||
res, err := e.app.startPluginDownload(e.h.Broker, e.notify, pluginID, e.roots, raw)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return res.(map[string]any)["id"].(string), nil
|
||||
}
|
||||
|
||||
// final waits for the last notification of a download and returns it.
|
||||
func (e *downloadTestEnv) final(t *testing.T, id string) downloadEvent {
|
||||
t.Helper()
|
||||
var last downloadEvent
|
||||
waitFor(t, "download "+id+" to finish", func() bool {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
for _, ev := range e.events {
|
||||
if ev.ID == id && ev.Status != "running" {
|
||||
last = ev
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
return last
|
||||
}
|
||||
|
||||
func sum(b []byte) string {
|
||||
s := sha256.Sum256(b)
|
||||
return hex.EncodeToString(s[:])
|
||||
}
|
||||
|
||||
func TestHostDownloadVerifiesAndReportsProgress(t *testing.T) {
|
||||
body := []byte(strings.Repeat("reims", 1000))
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/file.bin":
|
||||
_, _ = w.Write(body)
|
||||
case "/SHA256SUMS.txt":
|
||||
fmt.Fprintf(w, "%s other.bin\n%s file.bin\n", sum([]byte("x")), sum(body))
|
||||
case "/one.sha256":
|
||||
fmt.Fprintln(w, sum(body))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
e := newDownloadTestEnv(t, srv.URL)
|
||||
|
||||
cases := map[string]map[string]any{
|
||||
"explicit hash": {"url": srv.URL + "/file.bin", "sha256": sum(body), "dest": "a/file.bin"},
|
||||
"sums file": {"url": srv.URL + "/file.bin", "sha256_url": srv.URL + "/SHA256SUMS.txt", "sha256_name": "file.bin", "dest": "b/file.bin"},
|
||||
"single hash": {"url": srv.URL + "/file.bin", "sha256_url": srv.URL + "/one.sha256", "dest": "c/file.bin"},
|
||||
"no checksum": {"url": srv.URL + "/file.bin", "dest": "d/file.bin", "label": "plain"},
|
||||
}
|
||||
for name, req := range cases {
|
||||
id, err := e.start(t, e.plugin, req)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
ev := e.final(t, id)
|
||||
if ev.Status != "done" || ev.Path == "" {
|
||||
t.Fatalf("%s: final event = %+v", name, ev)
|
||||
}
|
||||
got, err := os.ReadFile(ev.Path)
|
||||
if err != nil || string(got) != string(body) {
|
||||
t.Fatalf("%s: file = %d bytes, %v", name, len(got), err)
|
||||
}
|
||||
if !pathInside(e.roots[0], ev.Path) {
|
||||
t.Fatalf("%s: %s is outside the plugin's data folder", name, ev.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostDownloadRejectsAWrongHashAndKeepsNoFile(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("payload")) }))
|
||||
defer srv.Close()
|
||||
e := newDownloadTestEnv(t, srv.URL)
|
||||
id, err := e.start(t, e.plugin, map[string]any{"url": srv.URL + "/x", "sha256": sum([]byte("something else")), "dest": "bad.bin"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ev := e.final(t, id); ev.Status != "failed" || !strings.Contains(ev.Error, "SHA256") {
|
||||
t.Fatalf("event = %+v", ev)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(e.roots[0], "bad.bin")); !os.IsNotExist(err) {
|
||||
t.Fatal("a download with the wrong hash was kept")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostDownloadChecksOriginsAndDestinations(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) }))
|
||||
defer srv.Close()
|
||||
denied := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("no")) }))
|
||||
defer denied.Close()
|
||||
e := newDownloadTestEnv(t, srv.URL) // a full http://127.0.0.1:port origin
|
||||
outside := filepath.Join(t.TempDir(), "out.bin")
|
||||
|
||||
bad := map[string]map[string]any{
|
||||
"undeclared origin": {"url": denied.URL + "/x", "dest": "a.bin"},
|
||||
"undeclared checksum": {"url": srv.URL + "/x", "sha256_url": denied.URL + "/sums", "dest": "a.bin"},
|
||||
"plain http to a remote": {"url": "http://example.com/x", "dest": "a.bin"},
|
||||
"url with user info": {"url": strings.Replace(srv.URL, "http://", "http://user:pw@", 1) + "/x", "dest": "a.bin"},
|
||||
"file scheme": {"url": "file:///C:/Windows/win.ini", "dest": "a.bin"},
|
||||
"dest above the folder": {"url": srv.URL + "/x", "dest": "../escaped.bin"},
|
||||
"dest elsewhere": {"url": srv.URL + "/x", "dest": outside},
|
||||
"empty dest": {"url": srv.URL + "/x", "dest": ""},
|
||||
"bad hash": {"url": srv.URL + "/x", "sha256": "zz", "dest": "a.bin"},
|
||||
}
|
||||
for name, req := range bad {
|
||||
if id, err := e.start(t, e.plugin, req); err == nil {
|
||||
t.Errorf("%s was accepted (download %s)", name, id)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(outside); !os.IsNotExist(err) {
|
||||
t.Fatal("a file was written outside the allowed folders")
|
||||
}
|
||||
// Another plugin without the permission cannot use this origin.
|
||||
if id, err := e.start(t, e.other, map[string]any{"url": srv.URL + "/x", "dest": "a.bin"}); err == nil {
|
||||
t.Fatalf("a plugin without the net permission started download %s", id)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostDownloadCancelIsPerPlugin(t *testing.T) {
|
||||
started := make(chan struct{}, 1)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Length", "1000000")
|
||||
_, _ = w.Write([]byte("start"))
|
||||
w.(http.Flusher).Flush()
|
||||
select {
|
||||
case started <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
defer srv.Close()
|
||||
e := newDownloadTestEnv(t, srv.URL, "127.0.0.1")
|
||||
id, err := e.start(t, e.plugin, map[string]any{"url": srv.URL + "/slow", "dest": "slow.bin"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("the download never reached the server")
|
||||
}
|
||||
cancelBy := func(plugin string) error {
|
||||
raw, _ := json.Marshal(map[string]any{"id": id})
|
||||
_, err := cancelPluginDownload(plugin, raw)
|
||||
return err
|
||||
}
|
||||
if err := cancelBy(e.other); err == nil {
|
||||
t.Fatal("a plugin cancelled another plugin's download")
|
||||
}
|
||||
if err := cancelBy(e.plugin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ev := e.final(t, id); ev.Status != "canceled" {
|
||||
t.Fatalf("event = %+v, want canceled", ev)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(e.roots[0], "slow.bin")); !os.IsNotExist(err) {
|
||||
t.Fatal("a cancelled download left its file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadRedirectsNeverDowngradeOrReachInternalHosts(t *testing.T) {
|
||||
client := safeDownloadClient("https://downloads.example.com/file")
|
||||
req := func(raw string) *http.Request {
|
||||
u, _ := url.Parse(raw)
|
||||
return &http.Request{URL: u}
|
||||
}
|
||||
via := []*http.Request{req("https://downloads.example.com/file")}
|
||||
cases := map[string]string{
|
||||
"downgrade to http": "http://8.8.8.8/x",
|
||||
"loopback": "https://127.0.0.1/x",
|
||||
"loopback name": "https://localhost/x",
|
||||
"private range": "https://10.1.2.3/x",
|
||||
"link local": "https://169.254.169.254/latest",
|
||||
"scheme change": "ftp://8.8.8.8/x",
|
||||
"user info": "https://u:p@8.8.8.8/x",
|
||||
}
|
||||
for name, target := range cases {
|
||||
if err := client.CheckRedirect(req(target), via); err == nil {
|
||||
t.Errorf("%s: redirect to %s was allowed", name, target)
|
||||
}
|
||||
}
|
||||
if err := client.CheckRedirect(req("https://8.8.8.8/x"), via); err != nil {
|
||||
t.Errorf("a plain HTTPS redirect to a public address was refused: %v", err)
|
||||
}
|
||||
long := make([]*http.Request, downloadMaxRedirects)
|
||||
for i := range long {
|
||||
long[i] = req("https://downloads.example.com/f")
|
||||
}
|
||||
if err := client.CheckRedirect(req("https://8.8.8.8/x"), long); err == nil {
|
||||
t.Error("an eleventh redirect was allowed")
|
||||
}
|
||||
// A loopback origin the plugin declared may redirect within loopback.
|
||||
local := safeDownloadClient("http://127.0.0.1:1/f")
|
||||
if err := local.CheckRedirect(req("http://127.0.0.1:1/g"), []*http.Request{req("http://127.0.0.1:1/f")}); err != nil {
|
||||
t.Errorf("a loopback redirect from a loopback origin was refused: %v", err)
|
||||
}
|
||||
_ = context.Background()
|
||||
}
|
||||
|
||||
func TestHasRunningDownloadFollowsPluginDownloads(t *testing.T) {
|
||||
m := &taskManager{tasks: map[string]*taskEntry{}}
|
||||
if m.hasRunningDownload() {
|
||||
t.Fatal("an empty task list reports a download")
|
||||
}
|
||||
id := m.start(taskKindPluginDownload, "x", "", func() {})
|
||||
if !m.hasRunningDownload() {
|
||||
t.Fatal("a running plugin download is not reported")
|
||||
}
|
||||
m.finish(id, "", nil)
|
||||
if m.hasRunningDownload() {
|
||||
t.Fatal("a finished download is still reported")
|
||||
}
|
||||
other := m.start("vm-create", "vm", "vm", func() {})
|
||||
if m.hasRunningDownload() {
|
||||
t.Fatal("a VM creation counts as a download")
|
||||
}
|
||||
m.finish(other, "", nil)
|
||||
}
|
||||
@@ -9,6 +9,7 @@ func (a *App) hostHandlers(mgr *plugin.Manager, pluginID string) map[string]plug
|
||||
for _, set := range []map[string]plugin.RPCRequestHandler{
|
||||
a.computerUseHostHandlers(mgr, pluginID),
|
||||
a.secretHostHandlers(mgr, pluginID),
|
||||
a.downloadHostHandlers(mgr, pluginID),
|
||||
} {
|
||||
for method, handler := range set {
|
||||
out[method] = handler
|
||||
|
||||
@@ -254,6 +254,23 @@ func (m *taskManager) cancel(id string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// hasRunningDownload reports whether a download is in progress: closing the
|
||||
// window would abort it, so the user is asked first.
|
||||
func (m *taskManager) hasRunningDownload() bool {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
for _, e := range m.tasks {
|
||||
if e.task.Status != TaskRunning {
|
||||
continue
|
||||
}
|
||||
switch e.task.Kind {
|
||||
case "installer-download", "recovery-download", "runtime-install", "app-update", taskKindPluginDownload:
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (m *taskManager) cancelAll() {
|
||||
m.mu.Lock()
|
||||
cancels := make([]context.CancelFunc, 0, len(m.tasks))
|
||||
|
||||
@@ -66,6 +66,9 @@ var catalog = map[Locale]map[string]string{
|
||||
"cli.usage.section_commands": "命令:",
|
||||
"cli.usage.section_usage": "用法:",
|
||||
"close": "关闭",
|
||||
"closeDownloadsConfirm": "退出",
|
||||
"closeDownloadsDesc": "仍有下载正在进行,退出会中断它们。",
|
||||
"closeDownloadsTitle": "退出 Reims-Go?",
|
||||
"closeWindow": "关闭",
|
||||
"collapseLogs": "收起日志",
|
||||
"compat.gpu_icd_rebound": "显卡 Vulkan ICD 路径已从 {old} 更新为 {new}",
|
||||
@@ -534,6 +537,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"taskAppUpdate": "下载 Reims-Go {v}",
|
||||
"taskCreate": "创建 {name}",
|
||||
"taskDownload": "下载 macOS {v}",
|
||||
"taskPluginDownload": "下载 {name}",
|
||||
"taskRecoveryDownload": "正在为 {name} 拉取并挂载在线恢复镜像",
|
||||
"taskRuntime": "安装运行时 {v}",
|
||||
"tasksRunning": "{n, plural, other {# 个任务进行中}}",
|
||||
@@ -726,6 +730,9 @@ var catalog = map[Locale]map[string]string{
|
||||
"cli.usage.section_commands": "Commands:",
|
||||
"cli.usage.section_usage": "Usage:",
|
||||
"close": "Close",
|
||||
"closeDownloadsConfirm": "Quit",
|
||||
"closeDownloadsDesc": "Downloads are still running. Quitting stops them.",
|
||||
"closeDownloadsTitle": "Quit Reims-Go?",
|
||||
"closeWindow": "Close",
|
||||
"collapseLogs": "Hide logs",
|
||||
"compat.gpu_icd_rebound": "Updated the GPU Vulkan ICD path from {old} to {new}",
|
||||
@@ -1194,6 +1201,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"taskAppUpdate": "Downloading Reims-Go {v}",
|
||||
"taskCreate": "Creating {name}",
|
||||
"taskDownload": "Downloading macOS {v}",
|
||||
"taskPluginDownload": "Downloading {name}",
|
||||
"taskRecoveryDownload": "Downloading online recovery for {name}",
|
||||
"taskRuntime": "Installing runtime {v}",
|
||||
"tasksRunning": "{n, plural, one {# task running} other {# tasks running}}",
|
||||
@@ -1461,6 +1469,7 @@ var paramOrder = map[string][]string{
|
||||
"taskAppUpdate": {"v"},
|
||||
"taskCreate": {"name"},
|
||||
"taskDownload": {"v"},
|
||||
"taskPluginDownload": {"name"},
|
||||
"taskRecoveryDownload": {"name"},
|
||||
"taskRuntime": {"v"},
|
||||
"tasksRunning": {"n"},
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -92,6 +94,102 @@ func (b *Broker) ResolveRefDriver(pluginID, driverID string) (string, error) {
|
||||
return b.resolveRefDriver(pluginID, driverID)
|
||||
}
|
||||
|
||||
// IsLoopbackHost reports whether host names this machine's loopback.
|
||||
func IsLoopbackHost(host string) bool {
|
||||
host = strings.ToLower(strings.TrimSpace(host))
|
||||
if host == "localhost" {
|
||||
return true
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
return ip != nil && ip.IsLoopback()
|
||||
}
|
||||
|
||||
func defaultPort(scheme string) string {
|
||||
if scheme == "http" {
|
||||
return "80"
|
||||
}
|
||||
return "443"
|
||||
}
|
||||
|
||||
// netPermissionMatches reports whether a declared `net:` permission covers u.
|
||||
// The permission is either a full origin (`net:https://host[:port]`) or a bare
|
||||
// host (`net:host`, `net:host:port`).
|
||||
func netPermissionMatches(permission string, u *url.URL) bool {
|
||||
spec, ok := strings.CutPrefix(strings.TrimSpace(permission), "net:")
|
||||
if !ok || strings.TrimSpace(spec) == "" {
|
||||
return false
|
||||
}
|
||||
spec = strings.ToLower(strings.TrimSpace(spec))
|
||||
host := strings.ToLower(u.Hostname())
|
||||
port := u.Port()
|
||||
if port == "" {
|
||||
port = defaultPort(u.Scheme)
|
||||
}
|
||||
if strings.Contains(spec, "://") {
|
||||
origin, err := url.Parse(spec)
|
||||
if err != nil || origin.Hostname() == "" || origin.Path != "" && origin.Path != "/" {
|
||||
return false
|
||||
}
|
||||
oPort := origin.Port()
|
||||
if oPort == "" {
|
||||
oPort = defaultPort(origin.Scheme)
|
||||
}
|
||||
return origin.Scheme == u.Scheme && strings.EqualFold(origin.Hostname(), host) && oPort == port
|
||||
}
|
||||
if h, p, err := net.SplitHostPort(spec); err == nil {
|
||||
return strings.EqualFold(h, host) && p == port
|
||||
}
|
||||
return spec == host
|
||||
}
|
||||
|
||||
// AuthorizeNetOrigin checks that pluginID is active and may reach rawURL: the
|
||||
// URL must name a `net:` origin the plugin declared, use HTTPS (plain HTTP is
|
||||
// allowed for loopback only) and carry no user info.
|
||||
func (b *Broker) AuthorizeNetOrigin(pluginID, rawURL string) error {
|
||||
u, err := url.Parse(strings.TrimSpace(rawURL))
|
||||
if err != nil || u.Host == "" || u.Hostname() == "" {
|
||||
return fmt.Errorf("invalid URL %q", rawURL)
|
||||
}
|
||||
if u.User != nil {
|
||||
b.Audit(pluginID, "DENY", "URL with user info")
|
||||
return errors.New("URLs with user info are not allowed")
|
||||
}
|
||||
switch u.Scheme {
|
||||
case "https":
|
||||
case "http":
|
||||
if !IsLoopbackHost(u.Hostname()) {
|
||||
b.Audit(pluginID, "DENY", "plain HTTP to "+u.Hostname())
|
||||
return fmt.Errorf("plain HTTP is only allowed for loopback hosts, not %q", u.Hostname())
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unsupported URL scheme %q", u.Scheme)
|
||||
}
|
||||
if b.reg == nil {
|
||||
return errors.New("registry unavailable")
|
||||
}
|
||||
info, ok := b.reg.Info(pluginID)
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown plugin %q", pluginID)
|
||||
}
|
||||
if info.State != StateActive && info.State != StateDegraded {
|
||||
return fmt.Errorf("plugin %q is not active (state=%s)", pluginID, info.State)
|
||||
}
|
||||
if info.NeedsApproval {
|
||||
return fmt.Errorf("plugin %q requires permission approval", pluginID)
|
||||
}
|
||||
for _, p := range info.Permissions {
|
||||
if netPermissionMatches(p.Name, u) {
|
||||
if !b.allowRate(pluginID, 120) {
|
||||
b.Audit(pluginID, "RATE_LIMIT", "net:"+u.Host)
|
||||
return fmt.Errorf("plugin %q exceeded Host API rate limit", pluginID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
b.Audit(pluginID, "DENY", "undeclared network origin "+u.Scheme+"://"+u.Host)
|
||||
return fmt.Errorf("plugin %q has not declared net:%s://%s", pluginID, u.Scheme, u.Host)
|
||||
}
|
||||
|
||||
func vmRefMapKey(driverID, name string) string {
|
||||
return strings.ToLower(strings.TrimSpace(driverID)) + "\x00" + strings.ToLower(strings.TrimSpace(name))
|
||||
}
|
||||
|
||||
@@ -172,7 +172,7 @@ var HostCapabilityCatalog = map[string]ContractStatus{
|
||||
"host.vm.spawn.ref": ContractStable,
|
||||
"host.vm.reportState": ContractStable,
|
||||
"driver.console": ContractStable,
|
||||
"host.download": ContractExperimental,
|
||||
"host.download": ContractStable,
|
||||
"host.elevate.request": ContractExperimental,
|
||||
"host.secret.materialize": ContractStable,
|
||||
}
|
||||
|
||||
@@ -13,13 +13,13 @@ func TestHostFeaturesAdvertiseGuestDriverContract(t *testing.T) {
|
||||
for _, want := range []string{
|
||||
"driver.snapshot", "driver.clone", "driver.disk", "driver.logs", "driver.phase", "driver.hosted",
|
||||
"driver.runtimeKind.external", "driver.pasteCombo", "driver.keymap", "host.vm.spawn.ref", "host.vm.reportState",
|
||||
"driver.console", "host.secret.materialize",
|
||||
"driver.console", "host.secret.materialize", "host.download",
|
||||
} {
|
||||
if !has[want] {
|
||||
t.Errorf("stable feature %s is not advertised", want)
|
||||
}
|
||||
}
|
||||
for _, unwanted := range []string{"host.download", "host.elevate.request"} {
|
||||
for _, unwanted := range []string{"host.elevate.request"} {
|
||||
if has[unwanted] {
|
||||
t.Errorf("experimental feature %s is advertised", unwanted)
|
||||
}
|
||||
|
||||
@@ -126,6 +126,21 @@ func (m *Manager) Layout() PluginsLayout { return m.layout }
|
||||
func (m *Manager) SafeMode() bool { return m.safeMode }
|
||||
func (m *Manager) CrashDetected() bool { return m.crashDetected }
|
||||
|
||||
// NotifySidecar sends a fire-and-forget notification (such as
|
||||
// `download/progress`) to pluginID's running Sidecar. It never wakes an idle
|
||||
// Sidecar and is a no-op when there is none.
|
||||
func (m *Manager) NotifySidecar(pluginID, method string, params any) {
|
||||
if m == nil {
|
||||
return
|
||||
}
|
||||
m.mu.RLock()
|
||||
supervisor := m.supervisors[pluginID]
|
||||
m.mu.RUnlock()
|
||||
if supervisor != nil {
|
||||
supervisor.NotifyIfRunning(method, params)
|
||||
}
|
||||
}
|
||||
|
||||
// ChannelMessage forwards one JSON line to a declared, active Sidecar channel.
|
||||
// Channel payloads are never written to the host audit log.
|
||||
func (m *Manager) ChannelMessage(ctx context.Context, pluginID, channelID string, message json.RawMessage) (json.RawMessage, error) {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNetPermissionMatchesOriginsAndHosts(t *testing.T) {
|
||||
parse := func(raw string) *url.URL {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return u
|
||||
}
|
||||
cases := []struct {
|
||||
permission, target string
|
||||
want bool
|
||||
}{
|
||||
{"net:https://cdn.example.com", "https://cdn.example.com/a/b.iso", true},
|
||||
{"net:https://cdn.example.com", "https://CDN.example.com:443/a", true},
|
||||
{"net:https://cdn.example.com", "http://cdn.example.com/a", false},
|
||||
{"net:https://cdn.example.com", "https://cdn.example.com:8443/a", false},
|
||||
{"net:https://cdn.example.com", "https://evil.example.com/a", false},
|
||||
{"net:https://cdn.example.com", "https://cdn.example.com.evil.net/a", false},
|
||||
{"net:cdn.example.com", "https://cdn.example.com/a", true},
|
||||
{"net:cdn.example.com", "https://sub.cdn.example.com/a", false},
|
||||
{"net:cdn.example.com:8443", "https://cdn.example.com:8443/a", true},
|
||||
{"net:cdn.example.com:8443", "https://cdn.example.com/a", false},
|
||||
{"net:http://127.0.0.1:9000", "http://127.0.0.1:9000/f", true},
|
||||
{"net:127.0.0.1", "http://127.0.0.1:9000/f", true},
|
||||
{"net:", "https://cdn.example.com/a", false},
|
||||
{"vm:read", "https://cdn.example.com/a", false},
|
||||
{"net:https://cdn.example.com/path", "https://cdn.example.com/a", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := netPermissionMatches(tc.permission, parse(tc.target)); got != tc.want {
|
||||
t.Errorf("netPermissionMatches(%q, %q) = %v, want %v", tc.permission, tc.target, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsLoopbackHost(t *testing.T) {
|
||||
for host, want := range map[string]bool{
|
||||
"localhost": true, "LOCALHOST": true, "127.0.0.1": true, "127.5.5.5": true, "::1": true,
|
||||
"example.com": false, "10.0.0.1": false, "": false,
|
||||
} {
|
||||
if got := IsLoopbackHost(host); got != want {
|
||||
t.Errorf("IsLoopbackHost(%q) = %v, want %v", host, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,13 @@ func NewHarness(t *testing.T) *Harness {
|
||||
// the host sees it. mode is "hosted" or "process"; the test binary must route
|
||||
// TestHelperFakeDriver to MaybeServe and TestHelperFakeVM to MaybeRunVM.
|
||||
func (h *Harness) Add(mode, pluginID, driverID string) driver.Driver {
|
||||
h.t.Helper()
|
||||
return h.AddWithPermissions(mode, pluginID, driverID)
|
||||
}
|
||||
|
||||
// AddWithPermissions is Add for a plugin that also declares extra permissions
|
||||
// (for example a `net:` origin).
|
||||
func (h *Harness) AddWithPermissions(mode, pluginID, driverID string, extra ...string) driver.Driver {
|
||||
h.t.Helper()
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
@@ -73,7 +80,7 @@ func (h *Harness) Add(mode, pluginID, driverID string) driver.Driver {
|
||||
if err := h.Registry.Register(plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
ID: pluginID, Version: "1.0.0", Name: plugin.LocalizedText{EnUS: pluginID},
|
||||
Permissions: []string{"driver:vm", "process:spawn", "vm:control"},
|
||||
Permissions: append([]string{"driver:vm", "process:spawn", "vm:control"}, extra...),
|
||||
Contributes: plugin.Contributes{GuestDrivers: []plugin.GuestDriverContribution{contrib}},
|
||||
},
|
||||
Source: plugin.SourceBuiltin, Desired: true,
|
||||
|
||||
@@ -67,6 +67,10 @@
|
||||
},
|
||||
"updateConfirmWin10": "This Windows 10 host relies on the cold-reboot workaround: the next time macOS in these VMs restarts, start the VM again by hand.",
|
||||
"taskAppUpdate": "Downloading Reims-Go {v}",
|
||||
"taskPluginDownload": "Downloading {name}",
|
||||
"closeDownloadsTitle": "Quit Reims-Go?",
|
||||
"closeDownloadsDesc": "Downloads are still running. Quitting stops them.",
|
||||
"closeDownloadsConfirm": "Quit",
|
||||
"settingsAbout": "About",
|
||||
"themeLight": "Light",
|
||||
"themeDark": "Dark",
|
||||
|
||||
@@ -67,6 +67,10 @@
|
||||
},
|
||||
"updateConfirmWin10": "这台 Windows 10 宿主依赖冷重启补偿:这些虚拟机里的 macOS 下次重启后不会自动开机,需要手动启动一次。",
|
||||
"taskAppUpdate": "下载 Reims-Go {v}",
|
||||
"taskPluginDownload": "下载 {name}",
|
||||
"closeDownloadsTitle": "退出 Reims-Go?",
|
||||
"closeDownloadsDesc": "仍有下载正在进行,退出会中断它们。",
|
||||
"closeDownloadsConfirm": "退出",
|
||||
"settingsAbout": "关于",
|
||||
"themeLight": "浅色",
|
||||
"themeDark": "深色",
|
||||
|
||||
@@ -449,6 +449,49 @@ func (s *Server) MaterializeSecret(ctx context.Context, req MaterializeSecretReq
|
||||
return resp.Path, err
|
||||
}
|
||||
|
||||
// DownloadRequest asks the host to download URL to Dest. The plugin must
|
||||
// declare a `net:` permission for the URL's origin (HTTPS, or HTTP for
|
||||
// loopback). Dest is relative to the plugin's data folder, or an absolute path
|
||||
// inside it or inside a VM root the plugin's driver declared. SHA256 (or
|
||||
// SHA256URL with SHA256Name selecting a line) makes the host verify the file.
|
||||
type DownloadRequest struct {
|
||||
URL string `json:"url"`
|
||||
SHA256 string `json:"sha256,omitempty"`
|
||||
SHA256URL string `json:"sha256_url,omitempty"`
|
||||
SHA256Name string `json:"sha256_name,omitempty"`
|
||||
Dest string `json:"dest"`
|
||||
Size int64 `json:"size,omitempty"`
|
||||
Label string `json:"label,omitempty"`
|
||||
}
|
||||
|
||||
// DownloadEvent is the payload of the host's `download/progress` notification.
|
||||
// Status is "running", "done", "failed" or "canceled".
|
||||
type DownloadEvent struct {
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Done int64 `json:"done"`
|
||||
Total int64 `json:"total"`
|
||||
Percent float64 `json:"percent"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// StartDownload has the host download a file in the background, with progress
|
||||
// in the host's task list. It returns the download ID that
|
||||
// `download/progress` notifications carry.
|
||||
func (s *Server) StartDownload(ctx context.Context, req DownloadRequest) (string, error) {
|
||||
var resp struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
err := s.CallHost(ctx, "host/download.start", req, &resp)
|
||||
return resp.ID, err
|
||||
}
|
||||
|
||||
// CancelDownload stops one of this plugin's downloads.
|
||||
func (s *Server) CancelDownload(ctx context.Context, id string) error {
|
||||
return s.CallHost(ctx, "host/download.cancel", map[string]any{"id": id}, nil)
|
||||
}
|
||||
|
||||
// DiscardSecret deletes the files the host materialized for ref's VM, or only
|
||||
// path when it is set. It returns how many files were removed.
|
||||
func (s *Server) DiscardSecret(ctx context.Context, ref VMRef, path string) (int, error) {
|
||||
|
||||
Reference in new issue
Block a user