fix: tighten plugin file grants and view handling
This commit is contained in:
1 parent
e8c278e58b
commit
36486a0850
7 files changed
+113
-22
No files matched your search
@@ -60,7 +60,7 @@ Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 V
|
||||
|
||||
`vm.get` 返回不含宿主路径的虚拟机详情。`settings.get` 与 `settings.set` 仅访问本插件清单声明的设置,校验类型、枚举、数值范围和 app/VM 作用域。访问 VM 级设置要求 `vm:read` 权限。秘密值读取时保持掩码,写入时沿用现有加密保存。`allow_ai_access` 记录用户对单台虚拟机的授权,只能由用户在宿主设置中修改。`storage.get`、`storage.set`、`storage.list` 与 `storage.delete` 提供按插件隔离且重启后保留的 JSON 键值存储,需要 `fs:plugin_data` 权限;存储键、单值与总大小均有上限,文件损坏时明确报错,不自动清空已有状态。
|
||||
|
||||
`file.pick` 与 `file.save` 通过原生对话框取得插件专属文件句柄,`file.read` 与 `file.write` 只接受这些句柄,不接受任意宿主路径,支持 UTF-8 和 Base64,单个文件上限为 8 MiB。`task.start`、`task.update` 与 `task.finish` 复用底部任务进度区,任务按插件归属校验,支持协作取消。页面关闭或重新加载时,宿主取消该页面未结束的任务;停用、卸载或切换数据目录会取消任务并撤销文件句柄。
|
||||
`file.pick` 与 `file.save` 通过原生对话框取得插件专属文件句柄,`file.read` 与 `file.write` 只接受这些句柄,不接受任意宿主路径,支持 UTF-8 和 Base64,单个文件上限为 8 MiB。每个插件最多同时持有 32 个文件句柄,句柄在签发 15 分钟后失效。`task.start`、`task.update` 与 `task.finish` 复用底部任务进度区,任务按插件归属校验,支持协作取消。页面关闭或重新加载时,宿主取消该页面未结束的任务;停用、卸载或切换数据目录会取消任务并撤销文件句柄。
|
||||
|
||||
`net.fetch` 按清单中的 `net:<主机>` 发起请求,支持文本、JSON 和 Base64 响应,重定向目标逐次重新授权,不回传 `Set-Cookie`。`events.subscribe` 与 `events.unsubscribe` 管理 `vm.stateChanged`、`view.visibilityChanged` 和 `task.updated` 订阅;VM 事件要求 `vm:read`,任务事件只发送本插件任务,视图可见性事件在订阅时先发送当前状态。`theme.changed` 与 `locale.changed` 无需订阅即会送达。
|
||||
|
||||
|
||||
+20
-9
@@ -23,7 +23,7 @@ import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFo
|
||||
import { hasVisibleDialog } from './lib/dialogState'
|
||||
import { latestVMStatsWithDriver, refreshSubscribedVMStats, refreshVMStatsWithDriver } from './lib/vmStats'
|
||||
import { vmRefKey } from './lib/vmRef'
|
||||
import { closePluginView, emptyPluginViewState, matchViewCondition, openPluginView, pluginViewKey, prunePluginViews, type PluginViewRoute, type PluginViewState } from './lib/pluginViewRouter'
|
||||
import { closePluginDialog, closePluginView, emptyPluginViewState, matchViewCondition, openPluginView, pluginViewKey, prunePluginViews, type PluginViewRoute, type PluginViewState } from './lib/pluginViewRouter'
|
||||
import { publishPluginHostEvent } from './lib/pluginViewEvents'
|
||||
import { buildSafePluginAssetURL } from './lib/pluginAssets'
|
||||
import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail, ViewContribution } from './types'
|
||||
@@ -287,7 +287,7 @@ export const App: React.FC = () => {
|
||||
const pluginViews = pluginUI?.views ?? []
|
||||
const findVM = (ref: string) => vms.find((item) => vmRefKey(item) === ref || item.name === ref)
|
||||
const viewAvailable = (view: ViewContribution, vmRef?: string) => {
|
||||
const vm = vmRef ? findVM(vmRef) : selectedVM
|
||||
const vm = vmRef ? findVM(vmRef) : undefined
|
||||
return matchViewCondition(view.when, { vmState: vm ? state?.transitions[vmRefKey(vm)] ?? vm.state : '', theme })
|
||||
}
|
||||
const openView = (view: ViewContribution, targetVM?: string) => {
|
||||
@@ -297,11 +297,19 @@ export const App: React.FC = () => {
|
||||
if (!target) throw new Error('A valid VM is required for this view')
|
||||
route.vm = vmRefKey(target)
|
||||
}
|
||||
if (!route.vm && view.when?.split('==')[0].trim() === 'vmState' && selectedVM) route.vm = vmRefKey(selectedVM)
|
||||
if (!viewAvailable(view, route.vm)) throw new Error('This view is not available in the current state')
|
||||
if (view.location === 'vm.tab') setSelectedPage(route.vm!)
|
||||
else if (view.location === 'settings') setSelectedPage(SETTINGS_ID)
|
||||
setPluginViewState((current) => openPluginView(current, route))
|
||||
}
|
||||
const openViewFromClick = (view: ViewContribution, targetVM?: string) => {
|
||||
try {
|
||||
openView(view, targetVM)
|
||||
} catch (error) {
|
||||
fail(tr('open'), error)
|
||||
}
|
||||
}
|
||||
const closeView = () => {
|
||||
const result = closePluginView(pluginViewState)
|
||||
setPluginViewState(result.state)
|
||||
@@ -349,13 +357,16 @@ export const App: React.FC = () => {
|
||||
metadata={pluginViewMeta[pluginViewKey(route)]}
|
||||
onMetadata={(metadata) => updateViewMetadata(view, metadata)}
|
||||
onOpenView={openView}
|
||||
onCloseView={closeView}
|
||||
onCloseView={dialog ? () => {
|
||||
setPluginViewState((current) => closePluginDialog(current, route))
|
||||
return { closed: true }
|
||||
} : closeView}
|
||||
onNavigate={navigateHost}
|
||||
/>
|
||||
)
|
||||
const renderVMTabs = () => {
|
||||
if (!selectedVM) return null
|
||||
const tabs = pluginViews.filter((view) => view.location === 'vm.tab' && viewAvailable(view))
|
||||
const tabs = pluginViews.filter((view) => view.location === 'vm.tab' && viewAvailable(view, vmRefKey(selectedVM)))
|
||||
if (tabs.length === 0) return null
|
||||
return (
|
||||
<div className="tabs rg-p-tabs" role="tablist" aria-label={tr('overview')}>
|
||||
@@ -367,7 +378,7 @@ export const App: React.FC = () => {
|
||||
const selectedTab = activePluginRoute?.location === 'vm.tab' && pluginViewKey(activePluginRoute) === key
|
||||
const badge = pluginViewMeta[key]?.badge
|
||||
return (
|
||||
<button key={key} type="button" role="tab" className="tab rg-p-tab" aria-selected={selectedTab} onClick={() => openView(view, vmRefKey(selectedVM))}>
|
||||
<button key={key} type="button" role="tab" className="tab rg-p-tab" aria-selected={selectedTab} onClick={() => openViewFromClick(view, vmRefKey(selectedVM))}>
|
||||
{locText(view.title, locale, view.id)}{badge ? ` · ${badge.text}` : ''}
|
||||
</button>
|
||||
)
|
||||
@@ -424,11 +435,11 @@ export const App: React.FC = () => {
|
||||
}
|
||||
const locale: Locale = resolveActiveLocale(state?.config.locale, pluginUI?.locales, state?.detected_locale)
|
||||
const dir = localeDir(locale)
|
||||
const settingsPluginViews = pluginViews.filter((view) => view.location === 'settings' && viewAvailable(view)).map((view) => {
|
||||
const settingsPluginViews = pluginViews.filter((view) => view.location === 'settings' && viewAvailable(view, selectedVM ? vmRefKey(selectedVM) : undefined)).map((view) => {
|
||||
const key = pluginViewKey({ pluginId: view.pluginId ?? '', viewId: view.id })
|
||||
return { id: key, title: locText(view.title, locale, view.id), badge: pluginViewMeta[key]?.badge?.text, onOpen: () => openView(view) }
|
||||
return { id: key, title: locText(view.title, locale, view.id), badge: pluginViewMeta[key]?.badge?.text, onOpen: () => openViewFromClick(view) }
|
||||
})
|
||||
const sidebarPluginViews = pluginViews.filter((view) => view.location === 'sidebar' && viewAvailable(view)).map((view) => {
|
||||
const sidebarPluginViews = pluginViews.filter((view) => view.location === 'sidebar' && viewAvailable(view, selectedVM ? vmRefKey(selectedVM) : undefined)).map((view) => {
|
||||
const key = pluginViewKey({ pluginId: view.pluginId ?? '', viewId: view.id })
|
||||
const icon = view.icon ? buildSafePluginAssetURL(pluginUI?.asset_token ?? '', view.pluginId, view.icon) ?? undefined : undefined
|
||||
return { id: `__plugin_view__:${key}`, view, title: locText(view.title, locale, view.id), badge: pluginViewMeta[key]?.badge?.text, icon }
|
||||
@@ -1268,7 +1279,7 @@ export const App: React.FC = () => {
|
||||
onSelect={(id) => {
|
||||
if (id.startsWith('__plugin_view__:')) {
|
||||
const item = sidebarPluginViews.find((entry) => entry.id === id)
|
||||
if (item) openView(item.view)
|
||||
if (item) openViewFromClick(item.view)
|
||||
} else {
|
||||
setSelected(id)
|
||||
}
|
||||
|
||||
@@ -57,6 +57,10 @@ export function closePluginView(state: PluginViewState): { state: PluginViewStat
|
||||
return { state: { route, dialogs: [], returnStack }, closed: true, page: state.route.from }
|
||||
}
|
||||
|
||||
export function closePluginDialog(state: PluginViewState, target: PluginViewRoute): PluginViewState {
|
||||
return { ...state, dialogs: state.dialogs.filter((route) => !sameRoute(route, target)) }
|
||||
}
|
||||
|
||||
export function prunePluginViews(
|
||||
state: PluginViewState,
|
||||
validViews: ReadonlySet<string>,
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
@@ -202,6 +203,33 @@ func TestPanelBridgeFileGrantLifecycle(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPluginFileGrantsExpireAndAreCapped(t *testing.T) {
|
||||
a := &App{}
|
||||
path := filepath.Join(t.TempDir(), "note.txt")
|
||||
var first string
|
||||
for range maxPluginFileGrants {
|
||||
grant, err := a.issuePluginFileGrant("vendor.panel", path, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first == "" {
|
||||
first = grant["id"].(string)
|
||||
}
|
||||
}
|
||||
if _, err := a.issuePluginFileGrant("vendor.panel", path, true); err == nil {
|
||||
t.Fatal("plugin exceeded its file grant limit")
|
||||
}
|
||||
grant := a.pluginFiles[first]
|
||||
grant.Expires = time.Now().Add(-time.Minute)
|
||||
a.pluginFiles[first] = grant
|
||||
if _, err := a.pluginFilePath("vendor.panel", first, true); err == nil {
|
||||
t.Fatal("expired file grant was accepted")
|
||||
}
|
||||
if _, err := a.issuePluginFileGrant("vendor.panel", path, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (fn roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return fn(req) }
|
||||
|
||||
@@ -10,18 +10,24 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
const maxPanelFileBytes = 8 << 20
|
||||
const (
|
||||
maxPanelFileBytes = 8 << 20
|
||||
maxPluginFileGrants = 32
|
||||
pluginFileGrantTTL = 15 * time.Minute
|
||||
)
|
||||
|
||||
type pluginFileGrant struct {
|
||||
PluginID string
|
||||
Path string
|
||||
Write bool
|
||||
Expires time.Time
|
||||
}
|
||||
|
||||
func (a *App) issuePluginFileGrant(pluginID, path string, write bool) (map[string]any, error) {
|
||||
@@ -37,21 +43,30 @@ func (a *App) issuePluginFileGrant(pluginID, path string, write bool) (map[strin
|
||||
return nil, err
|
||||
}
|
||||
id := hex.EncodeToString(token[:])
|
||||
a.mu.Lock()
|
||||
if a.pluginFiles == nil {
|
||||
a.pluginFiles = make(map[string]pluginFileGrant)
|
||||
}
|
||||
a.pluginFiles[id] = pluginFileGrant{PluginID: pluginID, Path: clean, Write: write}
|
||||
a.mu.Unlock()
|
||||
result := map[string]any{"id": id, "name": filepath.Base(clean), "write": write}
|
||||
if info, err := os.Stat(clean); err == nil {
|
||||
result["size"] = info.Size()
|
||||
} else if !write {
|
||||
a.mu.Lock()
|
||||
delete(a.pluginFiles, id)
|
||||
a.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
now := time.Now()
|
||||
count := 0
|
||||
for key, grant := range a.pluginFiles {
|
||||
if !now.Before(grant.Expires) {
|
||||
delete(a.pluginFiles, key)
|
||||
} else if grant.PluginID == pluginID {
|
||||
count++
|
||||
}
|
||||
}
|
||||
if count >= maxPluginFileGrants {
|
||||
return nil, errors.New("too many open file handles for this plugin")
|
||||
}
|
||||
if a.pluginFiles == nil {
|
||||
a.pluginFiles = make(map[string]pluginFileGrant)
|
||||
}
|
||||
a.pluginFiles[id] = pluginFileGrant{PluginID: pluginID, Path: clean, Write: write, Expires: now.Add(pluginFileGrantTTL)}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
@@ -67,8 +82,12 @@ func (a *App) revokePluginFiles(pluginID string) {
|
||||
|
||||
func (a *App) pluginFilePath(pluginID, id string, write bool) (string, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
grant, ok := a.pluginFiles[id]
|
||||
a.mu.Unlock()
|
||||
if ok && !time.Now().Before(grant.Expires) {
|
||||
delete(a.pluginFiles, id)
|
||||
ok = false
|
||||
}
|
||||
if !ok || grant.PluginID != pluginID || (write && !grant.Write) {
|
||||
return "", errors.New("file handle is not available to this plugin")
|
||||
}
|
||||
|
||||
@@ -1440,11 +1440,29 @@ func (r *Registry) RegisterView(sc *Scope, view ViewContribution) {
|
||||
if view.ID == "" {
|
||||
return
|
||||
}
|
||||
if _, ok := ViewLocationCatalog[view.Location]; !ok {
|
||||
location, ok := ViewLocationCatalog[view.Location]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
view.PluginID = sc.PluginID()
|
||||
r.mu.Lock()
|
||||
count := 0
|
||||
for _, existing := range r.views {
|
||||
if existing.PluginID != view.PluginID {
|
||||
continue
|
||||
}
|
||||
if existing.ID == view.ID {
|
||||
r.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if existing.Location == view.Location {
|
||||
count++
|
||||
}
|
||||
}
|
||||
if location.PerPlugin > 0 && count >= location.PerPlugin {
|
||||
r.mu.Unlock()
|
||||
return
|
||||
}
|
||||
r.views = append(r.views, view)
|
||||
r.mu.Unlock()
|
||||
sc.OnDispose(func() {
|
||||
|
||||
@@ -6,6 +6,17 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestViewRegistrationEnforcesIDsAndQuotas(t *testing.T) {
|
||||
reg := NewRegistry(nil)
|
||||
scope := newScope("vendor.views", reg)
|
||||
reg.RegisterView(scope, ViewContribution{ID: "first", Location: "settings"})
|
||||
reg.RegisterView(scope, ViewContribution{ID: "first", Location: "dialog"})
|
||||
reg.RegisterView(scope, ViewContribution{ID: "second", Location: "settings"})
|
||||
if views := reg.Views(""); len(views) != 1 || views[0].ID != "first" || views[0].Location != "settings" {
|
||||
t.Fatalf("views = %+v", views)
|
||||
}
|
||||
}
|
||||
|
||||
func TestViewsRegisterSortFindAndDispose(t *testing.T) {
|
||||
reg := NewRegistry(nil)
|
||||
manifest := Manifest{
|
||||
|
||||
Reference in new issue
Block a user