Files
kandev/apps/backend/cmd/plugin-fixture/main_test.go
T
João Salavisa e145d48f22 feat: add plugin system with grpc runtime and native ui plugins (#1742)
* feat: add plugin system with grpc runtime and native ui plugins

- go plugin backends ship as release tarballs (per-platform binaries, checksums) that
  kandev installs from url/upload or filesystem sideload+sync, then spawns and
  supervises via hashicorp/go-plugin (unix socket / loopback tcp+automtls)
- strict typed grpc contract (kandev.plugin.v1): DeliverEvent/InvokeTool/HandleWebhook
  plus a capability-gated host service (state, secrets, emit); author sdk in
  pkg/pluginsdk; packaging cli in cmd/plugin-pack
- native frontend bundles: window.registerKandevPlugin + registry/host loader with
  dynamic routes, nav items, slots and ws handlers; plugins settings page with
  install dialog, sync button and enable/disable/uninstall
- gated behind the plugins feature flag (prod off, dev/e2e on); covered by unit and
  integration tests plus playwright e2e against a real packaged fixture plugin

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): hydrate base app context on plugin routes

Plugin-owned SPA routes classify as RouteUnknown, so the boot payload shipped
only feature flags — no workspaces, workflows, or kanban context. Native plugin
UI (e.g. host.ui.TaskCreateDialog) then had an empty store. Hydrate the same
base context as the Home route for unknown SPA routes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(plugins): expose TaskCreateDialog on host.ui

Lets a native plugin open kandev's real create-task modal (prefilled via
initialValues) instead of POSTing directly.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): harden filesystem/URL sinks against CodeQL findings

Add sink-level guards on the plugin trust boundary: securejoin containment on
archive extraction (zip-slip), plugin-id validation before every fs_store path,
http/https scheme validation on install-from-URL, and non-interpolated ws-handler
error logging.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): address review findings (races, resource caps, lifecycle)

- serialize per-plugin startup to close a TOCTOU double-spawn race, and let a
  plugin restart after exhausting attempts
- bound plugin startup with an explicit 30s timeout
- reject backslash paths and cap decompressed bytes by actual size in pkgtar;
  only mark a package Signed when a verifier actually ran and passed
- delete plugin_state on uninstall; validate webhook keys against the manifest
  and cap webhook body size; restart an active plugin when a new version installs

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): sanitize plugin-id path sinks for CodeQL

Pin the plugin id to a single path segment with filepath.Base at recordPath/
configPath and pkgtar.Remove — a barrier the taint analysis recognizes.
Behaviour-identical for valid ids (already validated by safePluginID); clears
the go/path-injection alerts.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): inline plugin-id validation at path sinks for CodeQL

filepath.Base does not strip '..', so it is not a path-injection barrier. Call
the recognized safePluginID / id-pattern guard inline in Delete/GetConfig/
SetConfig and pkgtar.Remove — the same barrier that already cleared the Get sink.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): address code-review findings (backend)

- add capability-gating tests for the Host RPC service (was untested)
- close a stop-during-start orphan race so Disable/Uninstall can't leave a
  supervised subprocess behind
- on failed upgrade, remove only the new version dir (not all versions + data);
  restart the prior version
- validate manifest version and reject ids ending in .config (record-file alias)
- make Deliverer.Refresh non-blocking and cancel in-flight delivery on worker stop
- clamp out-of-range webhook status, skip-and-warn corrupt records in List,
  write records atomically, semver-aware sideload version pick

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): address code-review findings (frontend)

- wrap plugin routes + settings routes in a shared PluginErrorBoundary so a
  throwing plugin page shows a fallback instead of white-screening the SPA
- fix disable/re-enable in one session: keep the cached registration and
  re-run initialize instead of relying on a cached ES-module re-import
- prefix root-relative bundle/style URLs with apiBaseUrl (split-origin/Tauri)
- surface partial-install warnings via toast.warning instead of a bare success
- dedupe/remove injected style links on unload; gate PluginNavItems on the flag

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): serialize per-plugin lifecycle + guard config writes

- add a per-plugin keyed lock in Service so concurrent Enable/Disable/Install/
  Uninstall/UpdateConfig for one id are serialized (no status-machine race)
- take s.mu in SetConfig/GetConfig and write config atomically
- bound each plugin initialize() with a timeout so one hung bundle can't stall
  the rest of the boot load

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(plugins): split service_test.go to satisfy file-length lint

Move the install/URL test group into service_install_test.go; no logic change.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* ci: build and ship the e2e fixture plugin package to E2E shards

The plugin E2E specs' global-setup requires apps/backend/.build/kandev-plugin-e2e-1.0.0.tar.gz.
Build it in the E2E build job, upload it as an artifact, and download it in both
the regular and container shard jobs.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-17 12:00:26 +01:00

188 lines
5.8 KiB
Go

// Command plugin-fixture tests. Exercises fixturePlugin's Plugin methods
// (OnEvent, InvokeTool, HandleWebhook) via direct calls — no go-plugin
// spawn needed, since fixturePlugin has no dependency on the gRPC
// transport itself (pluginsdk.Serve owns that wiring and is covered by
// pkg/pluginsdk's own tests).
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"testing"
"github.com/kandev/kandev/pkg/pluginsdk"
"github.com/stretchr/testify/require"
)
var errBoom = errors.New("boom")
// readJSONLines reads path and decodes each non-empty line as T.
func readJSONLines[T any](t *testing.T, path string) []T {
t.Helper()
data, err := os.ReadFile(path)
require.NoError(t, err)
var out []T
scanner := bufio.NewScanner(bytes.NewReader(data))
for scanner.Scan() {
line := scanner.Bytes()
if len(bytes.TrimSpace(line)) == 0 {
continue
}
var v T
require.NoError(t, json.Unmarshal(line, &v))
out = append(out, v)
}
require.NoError(t, scanner.Err())
return out
}
func TestOnEvent_AppendsJSONLineToDataDir(t *testing.T) {
dir := t.TempDir()
p := &fixturePlugin{dataDir: dir}
err := p.OnEvent(context.Background(), &pluginsdk.Event{
EventID: "evt_1",
EventType: "task.created",
Payload: map[string]any{"task_id": "t1"},
})
require.NoError(t, err)
recs := readJSONLines[deliveryRecord](t, filepath.Join(dir, "deliveries.jsonl"))
require.Len(t, recs, 1)
require.Equal(t, "task.created", recs[0].EventType)
require.Equal(t, "evt_1", recs[0].EventID)
}
func TestOnEvent_AppendsMultipleDeliveriesInOrder(t *testing.T) {
dir := t.TempDir()
p := &fixturePlugin{dataDir: dir}
require.NoError(t, p.OnEvent(context.Background(), &pluginsdk.Event{EventID: "e1", EventType: "task.created"}))
require.NoError(t, p.OnEvent(context.Background(), &pluginsdk.Event{EventID: "e2", EventType: "task.updated"}))
recs := readJSONLines[deliveryRecord](t, filepath.Join(dir, "deliveries.jsonl"))
require.Len(t, recs, 2)
require.Equal(t, "e1", recs[0].EventID)
require.Equal(t, "e2", recs[1].EventID)
}
func TestOnEvent_CreatesDataDirIfMissing(t *testing.T) {
dir := filepath.Join(t.TempDir(), "nested", "data")
p := &fixturePlugin{dataDir: dir}
err := p.OnEvent(context.Background(), &pluginsdk.Event{EventID: "e1", EventType: "task.created"})
require.NoError(t, err)
_, err = os.Stat(filepath.Join(dir, "deliveries.jsonl"))
require.NoError(t, err)
}
func TestOnEvent_FirstEventCallsHostSetState(t *testing.T) {
dir := t.TempDir()
p := &fixturePlugin{dataDir: dir}
host := &fakeHost{}
p.SetHost(host)
require.NoError(t, p.OnEvent(context.Background(), &pluginsdk.Event{EventID: "e1", EventType: "task.created"}))
require.NoError(t, p.OnEvent(context.Background(), &pluginsdk.Event{EventID: "e2", EventType: "task.updated"}))
require.Len(t, host.setStateCalls, 1, "SetState should only be exercised on the first event")
call := host.setStateCalls[0]
require.Equal(t, "instance", call.scope)
require.Equal(t, "", call.scopeID)
require.Equal(t, "last_event", call.key)
require.Equal(t, "e1", call.value["event_id"])
}
func TestOnEvent_IgnoresHostSetStateError(t *testing.T) {
dir := t.TempDir()
p := &fixturePlugin{dataDir: dir}
host := &fakeHost{setStateErr: errBoom}
p.SetHost(host)
err := p.OnEvent(context.Background(), &pluginsdk.Event{EventID: "e1", EventType: "task.created"})
require.NoError(t, err, "Host.SetState failures must be best-effort and not fail OnEvent")
}
func TestInvokeTool_EchoReturnsInput(t *testing.T) {
p := &fixturePlugin{dataDir: t.TempDir()}
input := map[string]any{"channel": "#dev", "text": "hi"}
resp, err := p.InvokeTool(context.Background(), &pluginsdk.ToolRequest{
ToolName: "echo",
Input: input,
})
require.NoError(t, err)
require.Equal(t, input, resp.Output)
}
func TestHandleWebhook_AppendsJSONLineAndRespondsOK(t *testing.T) {
dir := t.TempDir()
p := &fixturePlugin{dataDir: dir}
resp, err := p.HandleWebhook(context.Background(), &pluginsdk.WebhookRequest{
WebhookKey: "test-hook",
Method: "POST",
Body: []byte(`{"ping":true}`),
})
require.NoError(t, err)
require.Equal(t, int32(200), resp.Status)
require.Equal(t, "ok", string(resp.Body))
recs := readJSONLines[webhookRecord](t, filepath.Join(dir, "webhooks.jsonl"))
require.Len(t, recs, 1)
require.Equal(t, "test-hook", recs[0].WebhookKey)
}
func TestResolveDataDir_UsesEnvWhenSet(t *testing.T) {
t.Setenv("KANDEV_PLUGIN_DATA_DIR", "/tmp/kandev-plugin-e2e-data")
require.Equal(t, "/tmp/kandev-plugin-e2e-data", resolveDataDir())
}
func TestResolveDataDir_FallsBackToCwdWhenUnset(t *testing.T) {
t.Setenv("KANDEV_PLUGIN_DATA_DIR", "")
wd, err := os.Getwd()
require.NoError(t, err)
require.Equal(t, wd, resolveDataDir())
}
// setStateCall records one fakeHost.SetState invocation.
type setStateCall struct {
scope, scopeID, key string
value map[string]any
}
// fakeHost is a minimal pluginsdk.Host test double that only records
// SetState calls; the fixture plugin never exercises the other methods.
type fakeHost struct {
setStateCalls []setStateCall
setStateErr error
}
func (h *fakeHost) GetState(context.Context, string, string, string) (map[string]any, bool, error) {
return nil, false, nil
}
func (h *fakeHost) SetState(_ context.Context, scope, scopeID, key string, value map[string]any) error {
h.setStateCalls = append(h.setStateCalls, setStateCall{scope: scope, scopeID: scopeID, key: key, value: value})
return h.setStateErr
}
func (h *fakeHost) DeleteState(context.Context, string, string, string) error { return nil }
func (h *fakeHost) ListState(context.Context, string, string) ([]pluginsdk.StateEntry, error) {
return nil, nil
}
func (h *fakeHost) RevealSecret(context.Context, string) (string, error) { return "", nil }
func (h *fakeHost) EmitEvent(context.Context, string, map[string]any) error { return nil }
var _ pluginsdk.Host = (*fakeHost)(nil)