Files
multica/server/internal/handler/plugin.go
T
f45b591623 MUL-6469: host plugin artifacts, bind installs to immutable versions (#7321)
* feat(plugins): host plugin artifacts, bind installs to immutable versions

A plugin used to be a URL. The manifest was frozen at install, but the surface
script was fetched from the author's server every time a panel opened, with no
integrity check — so an administrator consented to a manifest while the browser
ran whatever that host served that day, inside the scopes already granted. The
author's uptime was our uptime, every panel open leaked the reader's IP and
"who read which issue" to the author, and publishing at all required a public
HTTPS domain, which is why the repo's own deploy-sentinel example never ran.

The author now uploads an artifact bundle and Multica stores it:

- plugin_package / plugin_package_version / plugin_package_file. A version is
  insert-only, and the (package_id, version) unique index is what makes
  immutability a database rule rather than a convention.
- An installation names one version. Publishing another changes nothing for a
  workspace until an administrator upgrades, which is a second consent.
- The bundle is validated once, at publish: the manifest parses, every file it
  declares is present and loadable, and a surface entry with a top-level import
  is refused with the line named. That failure used to surface months later in
  a reader's browser.
- The host inlines the surface script into the document it generates, so the
  CSP names no remote script origin at all. `connect-src 'none'` now means it:
  a surface with no net: scope cannot reach anywhere, including its author.
- Install-by-URL is gone rather than kept alongside. Two paths would make "is
  this code frozen?" depend on how the plugin was installed.
- MULTICA_PLUGIN_DIR stays the development channel, but publishes an ordinary
  immutable version instead of being a second render path; re-publishing an
  unchanged version lands as `+dev.N`.

Hook endpoints and MCP servers remain on the author's own infrastructure.

Migration 376 drops existing installations: they name a source URL that is no
longer a concept, and the code they would run was never published here.
plugins_v1 has never left its feature flag and holds no production data — the
same call migration 344 made.

Closes MUL-6469

Co-authored-by: multica-agent <[email protected]>

* fix(plugins): serialize publish/install/delete, correct the isolation claim

Review of #7321 found five problems. Four are fixed here; the fifth is real,
needs its own design pass, and is now tracked and described honestly in the code
instead of claimed away.

Migration prefix collision. main took 376 for agent_task_durable_work_dir while
this branch was open, so `migration prefix 376 is reused` failed backend-tests.
Rebased and renumbered the six migrations to 377-382.

TOCTOU between delete and install/publish. Relationships are application-owned
by repository policy, so nothing made "the version this installation names still
exists" true across statements: `delete counts zero installs` -> `install reads
the version` -> `delete commits` -> `install commits` left an installation whose
panel 404s forever, and a publish racing a delete left a version whose package
row was gone. Publish, install and delete now hold a (workspace, plugin key)
advisory lock for their whole transaction, and delete counts installations
inside it. Both interleavings have regression tests that reproduce the bug with
the lock removed.

Failed publishes moved package state. upsertPackage ran before the version
transaction, so a republish that lost the unique index had already renamed the
package, and a first publish that failed afterwards left a plugin with zero
versions. It now runs inside the same transaction.

The top-level import check was wrong in BOTH directions. It read line prefixes,
so it missed `  import x` and `/* c */ import x` — and it refused a valid file
whose template literal contained the word at a line start, which is ordinary in
a surface that renders code samples. A refusal blocks a publish with no way
around it, so that false positive was the worse half. Replaced with a scanner
that skips comments and string/template literals; where it is imprecise it is
imprecise safely (`/` always reads as division), so a mistake can only cost a
detection, never invent one.

Sandbox self-navigation is NOT fixed. `sandbox="allow-scripts"` permits `_self`
navigation by design, no shipped CSP directive covers it, and contentWindow is
unchanged across it — so a hostile artifact can still reach its author once and
hand the replacement document the bridge port. Closing it needs an embedder
frame-src policy or a handshake a navigated document cannot complete; both are
decisions of their own. What lands here is damage control, labelled as such: the
generated document beacons on pagehide from a listener the plugin cannot detach,
and the embedder drops the bridge and unmounts the frame. The "a surface cannot
reach its author" wording is removed from the SDK README and the tests.

Closes MUL-6469
Refs MUL-6485

Co-authored-by: multica-agent <[email protected]>

* fix(plugins): harden surface validation and error reporting

* fix(migrations): renumber plugin package migrations

* fix(plugins): validate classic surfaces and reset failures

---------

Co-authored-by: Lambda <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-21 16:03:44 +08:00

331 lines
11 KiB
Go

package handler
import (
"context"
"encoding/json"
"errors"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/multica-ai/multica/server/internal/featureflags"
"github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/plugincontract"
)
func (h *Handler) pluginsV1Enabled(ctx context.Context) bool {
return featureflags.PluginsV1Enabled(ctx, h.FeatureFlags)
}
func (h *Handler) requirePluginsV1(w http.ResponseWriter, r *http.Request) bool {
if h.pluginsV1Enabled(r.Context()) {
return true
}
writeError(w, http.StatusServiceUnavailable, "Plugin management is not enabled")
return false
}
// writePluginError maps a service error onto a status. Kinds exist so the
// handler never has to string-match a message to pick a status code.
func writePluginError(w http.ResponseWriter, err error, fallback string) {
var pluginErr *service.PluginError
if !errors.As(err, &pluginErr) {
writeError(w, http.StatusInternalServerError, fallback)
return
}
switch pluginErr.Kind {
case service.PluginErrorInvalid:
writeError(w, http.StatusBadRequest, pluginErr.Message)
case service.PluginErrorNotFound:
writeError(w, http.StatusNotFound, pluginErr.Message)
case service.PluginErrorConflict:
writeError(w, http.StatusConflict, pluginErr.Message)
case service.PluginErrorForbidden:
writeError(w, http.StatusForbidden, pluginErr.Message)
case service.PluginErrorIncompatible:
writeError(w, http.StatusUnprocessableEntity, pluginErr.Message)
case service.PluginErrorQuota:
writeError(w, http.StatusInsufficientStorage, pluginErr.Message)
default:
writeError(w, http.StatusBadGateway, pluginErr.Message)
}
}
// pluginInstallationResponse never carries a secret value. `config` holds only
// non-secret fields by construction (SetConfig routes secrets to their own
// encrypted table), and configured secrets appear as names in
// `configured_secrets`.
type pluginInstallationResponse struct {
ID string `json:"id"`
PluginKey string `json:"plugin_key"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Version string `json:"version"`
// The published version this installation is bound to. Nothing about it can
// change under the workspace's feet: upgrading means pointing at a different
// version id, which is a second consent.
PackageVersionID string `json:"package_version_id"`
Enabled bool `json:"enabled"`
GrantedScopes []string `json:"granted_scopes"`
ConfigSchema []service.PluginConfigField `json:"config_schema"`
Config map[string]any `json:"config"`
ConfiguredSecrets []string `json:"configured_secrets"`
Surfaces []plugincontract.Surface `json:"surfaces"`
Hooks []pluginHookResponse `json:"hooks"`
Resources []plugincontract.Resource `json:"resources"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// pluginHookResponse omits input_schema: the settings page lists what a hook is
// and who may call it, and the raw JSON Schema is noise there.
type pluginHookResponse struct {
Key string `json:"key"`
Name string `json:"name"`
Description string `json:"description"`
Triggers []string `json:"triggers"`
Events []string `json:"events,omitempty"`
Transport string `json:"transport"`
}
func (h *Handler) pluginInstallationPayload(ctx context.Context, installation db.PluginInstallation) (pluginInstallationResponse, error) {
manifest, err := service.ParseInstallationManifest(installation)
if err != nil {
return pluginInstallationResponse{}, err
}
secrets, err := h.PluginService.ConfiguredSecretKeys(ctx, installation.ID)
if err != nil {
return pluginInstallationResponse{}, err
}
config := map[string]any{}
if len(installation.Config) > 0 {
_ = json.Unmarshal(installation.Config, &config)
}
var granted []string
if len(installation.GrantedScopes) > 0 {
_ = json.Unmarshal(installation.GrantedScopes, &granted)
}
if granted == nil {
granted = []string{}
}
hooks := make([]pluginHookResponse, 0, len(manifest.Contributes.Hooks))
for _, hook := range manifest.Contributes.Hooks {
hooks = append(hooks, pluginHookResponse{
Key: hook.Key,
Name: hook.Name,
Description: hook.Description,
Triggers: hook.Triggers,
Events: hook.Events,
Transport: hook.Transport.Type,
})
}
surfaces := manifest.Contributes.Surfaces
if surfaces == nil {
surfaces = []plugincontract.Surface{}
}
resources := manifest.Contributes.Resources
if resources == nil {
resources = []plugincontract.Resource{}
}
return pluginInstallationResponse{
ID: uuidToString(installation.ID),
PluginKey: installation.PluginKey,
Name: manifest.Name,
Description: manifest.Description,
Version: installation.Version,
PackageVersionID: uuidToString(installation.PackageVersionID),
Enabled: installation.Enabled,
GrantedScopes: granted,
ConfigSchema: service.ConfigFieldsForManifest(manifest),
Config: config,
ConfiguredSecrets: secrets,
Surfaces: surfaces,
Hooks: hooks,
Resources: resources,
CreatedAt: installation.CreatedAt.Time.UTC().Format(timeFormatRFC3339),
UpdatedAt: installation.UpdatedAt.Time.UTC().Format(timeFormatRFC3339),
}, nil
}
const timeFormatRFC3339 = "2006-01-02T15:04:05Z07:00"
// ListPlugins — GET /api/workspaces/{id}/plugins
func (h *Handler) ListPlugins(w http.ResponseWriter, r *http.Request) {
if !h.requirePluginsV1(w, r) {
return
}
workspaceID, ok := parseUUIDOrBadRequest(w, workspaceIDFromURL(r, "id"), "workspace_id")
if !ok {
return
}
installations, err := h.Queries.ListWorkspacePluginInstallations(r.Context(), workspaceID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list Plugins")
return
}
payloads := make([]pluginInstallationResponse, 0, len(installations))
for _, installation := range installations {
payload, err := h.pluginInstallationPayload(r.Context(), installation)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list Plugins")
return
}
payloads = append(payloads, payload)
}
writeJSON(w, http.StatusOK, map[string]any{"plugins": payloads})
}
type previewPluginRequest struct {
VersionID string `json:"version_id"`
}
// PreviewPlugin — POST /api/workspaces/{id}/plugins/preview
//
// Step one of the two-step install. Nothing is written: the response exists so
// the administrator can read the scope list before consenting.
func (h *Handler) PreviewPlugin(w http.ResponseWriter, r *http.Request) {
if !h.requirePluginsV1(w, r) {
return
}
workspaceID, ok := parseUUIDOrBadRequest(w, workspaceIDFromURL(r, "id"), "workspace_id")
if !ok {
return
}
var req previewPluginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
preview, err := h.PluginService.PreviewPlugin(r.Context(), workspaceID, req.VersionID)
if err != nil {
writePluginError(w, err, "failed to read the Plugin manifest")
return
}
writeJSON(w, http.StatusOK, preview)
}
type installPluginRequest struct {
VersionID string `json:"version_id"`
GrantedScopes []string `json:"granted_scopes"`
}
// InstallPlugin — POST /api/workspaces/{id}/plugins
func (h *Handler) InstallPlugin(w http.ResponseWriter, r *http.Request) {
if !h.requirePluginsV1(w, r) {
return
}
workspaceIDString := workspaceIDFromURL(r, "id")
workspaceID, ok := parseUUIDOrBadRequest(w, workspaceIDString, "workspace_id")
if !ok {
return
}
member, ok := h.workspaceMember(w, r, workspaceIDString)
if !ok {
return
}
var req installPluginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
installation, err := h.PluginService.InstallPlugin(r.Context(), workspaceID, member.UserID, req.VersionID, req.GrantedScopes)
if err != nil {
writePluginError(w, err, "failed to install the Plugin")
return
}
payload, err := h.pluginInstallationPayload(r.Context(), installation)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to install the Plugin")
return
}
writeJSON(w, http.StatusCreated, payload)
}
type configurePluginRequest struct {
Values map[string]any `json:"values"`
}
// ConfigurePlugin — PUT /api/workspaces/{id}/plugins/{installationId}/config
func (h *Handler) ConfigurePlugin(w http.ResponseWriter, r *http.Request) {
installation, ok := h.pluginInstallationFromURL(w, r)
if !ok {
return
}
var req configurePluginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
updated, err := h.PluginService.SetConfig(r.Context(), installation, req.Values)
if err != nil {
writePluginError(w, err, "failed to configure the Plugin")
return
}
payload, err := h.pluginInstallationPayload(r.Context(), updated)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to configure the Plugin")
return
}
writeJSON(w, http.StatusOK, payload)
}
// EnablePlugin — POST /api/workspaces/{id}/plugins/{installationId}/enable
func (h *Handler) EnablePlugin(w http.ResponseWriter, r *http.Request) {
h.setPluginEnabled(w, r, true)
}
// DisablePlugin — POST /api/workspaces/{id}/plugins/{installationId}/disable
func (h *Handler) DisablePlugin(w http.ResponseWriter, r *http.Request) {
h.setPluginEnabled(w, r, false)
}
func (h *Handler) setPluginEnabled(w http.ResponseWriter, r *http.Request, enabled bool) {
installation, ok := h.pluginInstallationFromURL(w, r)
if !ok {
return
}
updated, err := h.PluginService.SetEnabled(r.Context(), installation, enabled)
if err != nil {
writePluginError(w, err, "failed to update the Plugin")
return
}
payload, err := h.pluginInstallationPayload(r.Context(), updated)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to update the Plugin")
return
}
writeJSON(w, http.StatusOK, payload)
}
// UninstallPlugin — DELETE /api/workspaces/{id}/plugins/{installationId}
func (h *Handler) UninstallPlugin(w http.ResponseWriter, r *http.Request) {
installation, ok := h.pluginInstallationFromURL(w, r)
if !ok {
return
}
if err := h.PluginService.Uninstall(r.Context(), installation); err != nil {
writePluginError(w, err, "failed to uninstall the Plugin")
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *Handler) pluginInstallationFromURL(w http.ResponseWriter, r *http.Request) (db.PluginInstallation, bool) {
if !h.requirePluginsV1(w, r) {
return db.PluginInstallation{}, false
}
workspaceID, ok := parseUUIDOrBadRequest(w, workspaceIDFromURL(r, "id"), "workspace_id")
if !ok {
return db.PluginInstallation{}, false
}
installation, err := h.PluginService.InstallationForWorkspace(r.Context(), workspaceID, chi.URLParam(r, "installationId"))
if err != nil {
writePluginError(w, err, "failed to load the Plugin")
return db.PluginInstallation{}, false
}
return installation, true
}