fix(yaegiutil): refuse incomplete Yaegi interface wrappers at load

The generated symbol tables carried 25 hand-added nil guards across three
packages, re-applied by hand after every regeneration because `yaegi extract`
does not emit them. Regeneration silently dropped them, and three package docs
instructed the next agent to put them back.

The guards also answered the wrong way. A nil WResolve returned ("", nil), so a
malformed secret engine served an empty secret and reported success; a nil
WStop reported a clean shutdown for a module that never ran one.

Reject the wrapper where it enters the daemon instead. Yaegi type-checks
"var X Iface = impl{}" and refuses an incomplete impl on its own, but the
wrapper type is exported into the symbol table, so interpreted code can build
one directly and struct-literal semantics leave the omitted method nil.
Resolve now names the missing method and skips the plugin.

Generated tables are used verbatim again. Also names the wanted type on a
failed assertion, which formatted as "want <nil>" for every interface target.
This commit is contained in:
sam committed 2026-09-20 12:05:39 +10:00
1 parent b2fcf25c0b
commit d4ce6799b6
16 files changed
+212 -361

No files matched your search

+5 -3
View File
@@ -18,9 +18,11 @@ import (
"github.com/samcharles93/archie-core/internal/yaegiutil"
)
// Plugin is a core plugin loaded by the daemon at startup. Each .go file
// in ~/.config/archie/plugins/ must export a variable named "Plugin" that
// satisfies this interface.
// Plugin is a core plugin loaded by the daemon at startup. Each .go file in
// ~/.config/archie/plugins/ must export a variable named "Plugin" declared
// with an interface type: "var Plugin plugin.Plugin = impl{}". A
// concrete-typed export is refused, because Yaegi only bridges an interpreted
// value to Go as an interface when the declaration names one.
type Plugin interface {
Name() string
Version() string
+100 -71
View File
@@ -3,11 +3,16 @@ package plugin_test
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
"github.com/traefik/yaegi/interp"
"github.com/samcharles93/archie-core/internal/plugin"
"github.com/samcharles93/archie-core/internal/plugin/pluginextract"
"github.com/samcharles93/archie-core/internal/yaegiutil"
)
// ── Plugin interface ─────────────────────────────────────────────────
@@ -22,6 +27,65 @@ func TestPluginInterfaceExists(t *testing.T) {
var _ nameVersioner = p
}
func TestPartialImplementationIsRejectedBeforeWrapping(t *testing.T) {
// Why the generated interface wrappers carry no nil-guards: Yaegi
// type-checks the assignment to the interface before it ever builds a
// wrapper, so a type missing a method never reaches Go as a wrapper with
// a nil method field. Guarding the generated wrappers by hand defends a
// state Yaegi cannot produce, and every regeneration silently drops it.
i, err := yaegiutil.New(interp.Options{}, symbols)
if err != nil {
t.Fatal(err)
}
_, err = yaegiutil.Resolve[plugin.Plugin](i, `package main
import "github.com/samcharles93/archie-core/internal/plugin"
type partial struct{}
func (partial) Name() string { return "partial" }
var Plugin plugin.Plugin = partial{}
`, "main.Plugin")
if err == nil {
t.Fatal("want error for a Plugin missing Version(), got nil")
}
if !strings.Contains(err.Error(), "cannot use type") {
t.Errorf("want a Yaegi assignment type error, got: %v", err)
}
}
func TestCompleteImplementationWrapsWithNoNilMethods(t *testing.T) {
i, err := yaegiutil.New(interp.Options{}, symbols)
if err != nil {
t.Fatal(err)
}
p, err := yaegiutil.Resolve[plugin.Plugin](i, `package main
import "github.com/samcharles93/archie-core/internal/plugin"
type complete struct{}
func (complete) Name() string { return "n" }
func (complete) Version() string { return "v" }
var Plugin plugin.Plugin = complete{}
`, "main.Plugin")
if err != nil {
t.Fatal(err)
}
rv := reflect.ValueOf(p)
if rv.Kind() != reflect.Struct {
t.Fatalf("want a Yaegi wrapper struct, got %T", p)
}
for j := range rv.NumField() {
f := rv.Type().Field(j)
if f.Type.Kind() == reflect.Func && rv.Field(j).IsNil() {
t.Errorf("wrapper field %s is nil; Yaegi is expected to populate every method", f.Name)
}
}
}
// ── LoadDir behavioral tests ─────────────────────────────────────────
var symbols = pluginextract.Symbols
@@ -178,11 +242,10 @@ func TestLoadDirNonexistentDirReturnsNil(t *testing.T) {
// These tests try to BREAK LoadDir. A correct implementation must
// degrade gracefully -- skip the bad plugin, load the rest, never panic.
func TestLoadDirNilFunctionFieldsLoadsWithoutPanic(t *testing.T) {
// A _Plugin with nil WName/WVersion must LOAD without panicking
// AND must not panic when Name()/Version() is called -- the wrapper
// must nil-guard. Otherwise logging plugin names at startup crashes
// the daemon.
func TestLoadDirRefusesWrapperWithNilFunctionFields(t *testing.T) {
// A _Plugin with nil WName/WVersion must be refused at load. It
// previously loaded and answered "" for both, so the daemon logged a
// nameless plugin as if it were healthy.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "nilfuncs.go"), []byte(`package main
@@ -200,19 +263,8 @@ var Plugin = plugin._Plugin{
if err != nil {
t.Fatal(err)
}
if len(plugins) != 1 {
t.Fatalf("LoadDir returned %d plugins, want 1 (nil funcs should not prevent loading)", len(plugins))
}
// These must not panic -- the _Plugin wrapper must nil-guard.
// The daemon calls Name()/Version() at startup to log loaded plugins.
name := plugins[0].Name()
version := plugins[0].Version()
if name != "" {
t.Errorf("Name() = %q, want empty string from nil WName", name)
}
if version != "" {
t.Errorf("Version() = %q, want empty string from nil WVersion", version)
if len(plugins) != 0 {
t.Fatalf("LoadDir returned %d plugins, want 0 (a wrapper missing methods must be refused)", len(plugins))
}
}
@@ -284,6 +336,32 @@ var Plugin partial
}
}
func TestLoadDirSkipsHandBuiltPartialWrapper(t *testing.T) {
// Yaegi type-checks "var Plugin plugin.Plugin = impl{}" and refuses an
// incomplete impl, but interpreted code can also build the generated
// wrapper directly, where struct-literal semantics leave an omitted method
// nil and the call panics at first use. LoadDir must refuse it instead.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "partialwrap.go"), []byte(`package main
import "github.com/samcharles93/archie-core/internal/plugin"
var Plugin = plugin._Plugin{
WName: func() string { return "halfbuilt" },
}
`), 0o644); err != nil {
t.Fatal(err)
}
plugins, err := plugin.LoadDir(dir, symbols)
if err != nil {
t.Fatal(err)
}
if len(plugins) != 0 {
t.Fatalf("LoadDir returned %d plugins from a wrapper missing WVersion, want 0", len(plugins))
}
}
func TestLoadDirEmptyDirReturnsEmptySlice(t *testing.T) {
dir := t.TempDir()
plugins, err := plugin.LoadDir(dir, symbols)
@@ -383,59 +461,10 @@ var Plugin = struct{}{}
_ = plugins
}
func TestGeneratedWrapperHasNilGuards(t *testing.T) {
// C4: the generated _Plugin wrapper must nil-guard WName and WVersion.
// If go generate strips these guards, the daemon panics at startup
// when logging plugin names. This test verifies the guards exist
// and will fail if someone regenerates without them.
//
// The _Plugin type is in the pluginextract package. We verify
// indirectly by loading a plugin with nil funcs and calling
// Name()/Version() -- they must return empty strings, not panic.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "nilguard.go"), []byte(`package main
import "github.com/samcharles93/archie-core/internal/plugin"
var Plugin = plugin._Plugin{
WName: nil,
WVersion: nil,
}
`), 0o644); err != nil {
t.Fatal(err)
}
plugins, err := plugin.LoadDir(dir, symbols)
if err != nil {
t.Fatal(err)
}
if len(plugins) != 1 {
t.Fatal("plugin with nil funcs not loaded")
}
// These must not panic. If they do, go generate was run and stripped
// the nil guards from the generated wrapper.
var name, version string
func() {
defer func() {
if r := recover(); r != nil {
t.Fatalf("Name()/Version() panicked with nil funcs -- "+
"the generated _Plugin wrapper is missing nil guards. "+
"Re-run `go generate` may have overwritten them: %v", r)
}
}()
name = plugins[0].Name()
version = plugins[0].Version()
}()
if name != "" {
t.Errorf("Name() = %q, want empty from nil WName", name)
}
if version != "" {
t.Errorf("Version() = %q, want empty from nil WVersion", version)
}
}
// The former TestGeneratedWrapperHasNilGuards was retired. It pinned
// hand-added nil guards in the generated wrapper, which every regeneration
// silently dropped. LoadDir now refuses such a plugin outright; see
// TestLoadDirRefusesWrapperWithNilFunctionFields.
func TestLoadDirPluginWithGoBuildTag(t *testing.T) {
// Build tags in Yaegi-interpreted code are just comments -- they
@@ -41,21 +41,12 @@ type _github_com_samcharles93_archie_core_internal_plugin_Module struct {
}
func (W _github_com_samcharles93_archie_core_internal_plugin_Module) Manifest() plugin.Manifest {
if W.WManifest == nil {
return plugin.Manifest{}
}
return W.WManifest()
}
func (W _github_com_samcharles93_archie_core_internal_plugin_Module) Start(a0 context.Context) error {
if W.WStart == nil {
return nil
}
return W.WStart(a0)
}
func (W _github_com_samcharles93_archie_core_internal_plugin_Module) Stop(a0 context.Context) error {
if W.WStop == nil {
return nil
}
return W.WStop(a0)
}
@@ -67,14 +58,8 @@ type _github_com_samcharles93_archie_core_internal_plugin_Plugin struct {
}
func (W _github_com_samcharles93_archie_core_internal_plugin_Plugin) Name() string {
if W.WName == nil {
return ""
}
return W.WName()
}
func (W _github_com_samcharles93_archie_core_internal_plugin_Plugin) Version() string {
if W.WVersion == nil {
return ""
}
return W.WVersion()
}
@@ -2,11 +2,9 @@
// generated by `go generate`. Kept separate from internal/plugin itself
// so the generated file can import it without a self-import cycle.
//
// IMPORTANT: Running `go generate` overwrites the generated file with
// Yaegi's default wrapper which does NOT include nil-guards on function
// fields. The `TestGeneratedWrapperHasNilGuards` test catches this if
// regeneration strips the guards. Re-apply nil-guards manually after
// regeneration until Yaegi supports generating them natively.
// The generated file is used verbatim. A wrapper whose method fields are not
// all populated is refused in yaegiutil.Resolve, so it needs no hand-added
// nil-guards -- an earlier convention that every regeneration silently undid.
package pluginextract
import "reflect"
@@ -27,32 +27,10 @@ func TestSymbolsContainsExpectedPluginEntries(t *testing.T) {
}
}
func TestGeneratedWrapperHasNilGuards(t *testing.T) {
// Regression: go generate strips nil-guards from _Plugin wrapper.
// Verify that Plugin is present in the Symbols table and is an
// interface type (as expected for yaegi interface extraction).
pkgKey := "github.com/samcharles93/archie-core/internal/plugin/plugin"
pkg := Symbols[pkgKey]
pluginType, ok := pkg["Plugin"]
if !ok {
t.Fatal("Plugin missing from Symbols")
}
// Plugin is an interface type — yaegi represents interfaces
// differently from struct pointers.
kind := pluginType.Kind()
if kind != reflect.Interface && kind != reflect.Pointer {
t.Errorf("Plugin type kind = %v, want Interface or Ptr", kind)
}
// Verify WName and WVersion exist on the Plugin interface type.
// For interface types, we check the method set.
if kind == reflect.Interface {
methodCount := pluginType.Type().NumMethod()
if methodCount < 2 {
t.Errorf("Plugin interface has %d methods, expected at least 2 (Name, Version)", methodCount)
}
}
}
// The former TestGeneratedWrapperHasNilGuards was retired: it was named for a
// regression Yaegi cannot produce. Yaegi type-checks the assignment to an
// interface before building a wrapper, so a wrapper never reaches Go with a nil
// method field, and the hand-added guards it referred to only survived until the
// next regeneration. That invariant is pinned directly in internal/plugin by
// TestPartialImplementationIsRejectedBeforeWrapping and
// TestCompleteImplementationWrapsWithNoNilMethods.
@@ -89,29 +89,10 @@ func (testModule) Manifest() plugin.Manifest {
func (testModule) Start(context.Context) error { return nil }
func (testModule) Stop(context.Context) error { return nil }
// TestWrapperNilGuardsPreserved follows the established pattern: yaegi's
// fresh wrapper generation omits nil-guards on interface-wrappers, so they
// are re-applied by hand after every regeneration. A zero-value wrapper
// (all function fields nil) must not panic.
func TestWrapperNilGuardsPreserved(t *testing.T) {
var mod _github_com_samcharles93_archie_core_internal_plugin_Module
if err := mod.Start(context.Background()); err != nil {
t.Errorf("Start on nil WStart = %v, want nil", err)
}
if got := mod.Manifest(); got.ID != "" || got.Name != "" || got.APIVersion != "" {
t.Errorf("Manifest on nil WManifest = %#v, want empty", got)
}
if err := mod.Stop(context.Background()); err != nil {
t.Errorf("Stop on nil WStop = %v, want nil", err)
}
var legacy _github_com_samcharles93_archie_core_internal_plugin_Plugin
if got := legacy.Name(); got != "" {
t.Errorf("Name on nil WName = %q, want empty", got)
}
if got := legacy.Version(); got != "" {
t.Errorf("Version on nil WVersion = %q, want empty", got)
}
}
// The former TestWrapperNilGuardsPreserved was retired. It pinned hand-added
// nil guards that every regeneration silently dropped, and the behaviour it
// protected was a lie: a nil WStop reported a clean shutdown for a module that
// never ran one. Such a wrapper is now refused in yaegiutil.Resolve, before it
// can reach a call site.
var _ plugin.Module = testModule{}