diff --git a/pkg/catalog/catalog.go b/pkg/catalog/catalog.go index 6f52a9d..d9efd44 100644 --- a/pkg/catalog/catalog.go +++ b/pkg/catalog/catalog.go @@ -116,6 +116,10 @@ func New(ctx context.Context, config Config, repo api.Repository, builtIns ...Bu continue } + for _, opt := range config.PluginOptions { + opt(&pluginConfig) + } + pluginConfig.HostServices = config.HostServices pluginRepo, ok := pluginRepos[pluginConfig.Type] diff --git a/pkg/catalog/catalog_model.go b/pkg/catalog/catalog_model.go index 67f3578..5fab0a7 100644 --- a/pkg/catalog/catalog_model.go +++ b/pkg/catalog/catalog_model.go @@ -23,4 +23,12 @@ type Config struct { // HostServices are the servers for host services provided by SPIRE to // plugins. HostServices []api.ServiceServer + + // PluginOptions are applied to every PluginConfig when the catalog is + // created. Use them to inject cross-cutting behaviour such as a middleware. + PluginOptions []PluginOption } + +// PluginOption mutates a PluginConfig. Options supplied via Config.PluginOptions +// are applied to every plugin before it is loaded. +type PluginOption func(*PluginConfig) diff --git a/pkg/catalog/catalog_test.go b/pkg/catalog/catalog_test.go new file mode 100644 index 0000000..7ac215d --- /dev/null +++ b/pkg/catalog/catalog_test.go @@ -0,0 +1,59 @@ +package catalog + +import ( + "bytes" + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/openkcm/plugin-sdk/api" + "github.com/openkcm/plugin-sdk/pkg/plugin" + testv1 "github.com/openkcm/plugin-sdk/proto/plugin/test/v1" +) + +type testRepo struct { + client *testServiceFacade +} + +func (r *testRepo) Plugins() map[string]api.PluginRepo { + return map[string]api.PluginRepo{testv1.Type: r} +} +func (r *testRepo) Services() []api.ServiceRepo { return nil } +func (r *testRepo) Binder() any { return func(c *testServiceFacade) { r.client = c } } +func (r *testRepo) Versions() []api.Version { return []api.Version{testServiceV1{}} } +func (r *testRepo) Constraints() api.Constraints { return api.ExactlyOne() } +func (r *testRepo) Clear() { r.client = nil } + +type testServiceV1 struct{} + +func (testServiceV1) New() api.Facade { return new(testServiceFacade) } +func (testServiceV1) Deprecated() bool { return false } + +type testServiceFacade struct { + plugin.Facade + testv1.TestServicePluginClient +} + +func TestCatalog_WithErrorLogging(t *testing.T) { + repo := &testRepo{} + var buf bytes.Buffer + + cat, err := New(context.Background(), Config{ + Logger: newTestLogger(&buf), + PluginConfigs: []PluginConfig{{ + Name: "testplugin", + Type: testv1.Type, + Path: "./testpluginbinary", + }}, + PluginOptions: []PluginOption{WithErrorLogging(newTestLogger(&buf))}, + }, repo) + require.NoError(t, err) + defer cat.Close() + + _, err = repo.client.Test(context.Background(), &testv1.TestRequest{}) + require.NoError(t, err) + + assert.NotContains(t, buf.String(), "plugin method returned error") +} diff --git a/pkg/catalog/options.go b/pkg/catalog/options.go new file mode 100644 index 0000000..11b96bd --- /dev/null +++ b/pkg/catalog/options.go @@ -0,0 +1,32 @@ +package catalog + +import ( + "context" + "log/slog" + + "google.golang.org/grpc" +) + +// WithErrorLogging returns a PluginOption that logs every gRPC error returned by the plugin +func WithErrorLogging(logger *slog.Logger) PluginOption { + return func(cfg *PluginConfig) { + cfg.unaryInterceptors = append(cfg.unaryInterceptors, func( + ctx context.Context, + method string, + req, reply any, + cc *grpc.ClientConn, + invoker grpc.UnaryInvoker, + opts ...grpc.CallOption, + ) error { + err := invoker(ctx, method, req, reply, cc, opts...) + if err != nil { + logger.ErrorContext(ctx, "plugin method returned error", + slog.String("pluginName", cfg.Name), + slog.String("method", method), + slog.String("error", err.Error()), + ) + } + return err + }) + } +} diff --git a/pkg/catalog/options_test.go b/pkg/catalog/options_test.go new file mode 100644 index 0000000..fb7ef68 --- /dev/null +++ b/pkg/catalog/options_test.go @@ -0,0 +1,85 @@ +package catalog + +import ( + "bytes" + "context" + "errors" + "log/slog" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" +) + +func newTestLogger(buf *bytes.Buffer) *slog.Logger { + return slog.New(slog.NewTextHandler(buf, nil)) +} + +func fakeInvoker(err error) grpc.UnaryInvoker { + return func(_ context.Context, _ string, _, _ any, _ *grpc.ClientConn, _ ...grpc.CallOption) error { + return err + } +} + +func TestWithErrorLogging(t *testing.T) { + t.Parallel() + + t.Run("Should log on error", func(t *testing.T) { + var buf bytes.Buffer + cfg := &PluginConfig{Name: "my-plugin"} + WithErrorLogging(newTestLogger(&buf))(cfg) + + err := cfg.unaryInterceptors[0](context.Background(), "/svc/Method", nil, nil, nil, fakeInvoker(errors.New("boom"))) + + require.Error(t, err) + assert.Contains(t, buf.String(), "my-plugin") + assert.Contains(t, buf.String(), "boom") + assert.Contains(t, buf.String(), "/svc/Method") + }) + + t.Run("Should not log on success", func(t *testing.T) { + var buf bytes.Buffer + cfg := &PluginConfig{Name: "my-plugin"} + WithErrorLogging(newTestLogger(&buf))(cfg) + + require.NoError(t, cfg.unaryInterceptors[0](context.Background(), "/svc/Method", nil, nil, nil, fakeInvoker(nil))) + assert.Empty(t, buf.String()) + }) +} + +func TestGetDialOptions_EmptyWithNoInterceptors(t *testing.T) { + t.Parallel() + + assert.Empty(t, (&PluginConfig{}).getDialOptions()) +} + +func TestGetDialOptions_SingleChainForMultipleInterceptors(t *testing.T) { + t.Parallel() + + var buf bytes.Buffer + cfg := &PluginConfig{Name: "p"} + WithErrorLogging(newTestLogger(&buf))(cfg) + WithErrorLogging(newTestLogger(&buf))(cfg) + + assert.Len(t, cfg.unaryInterceptors, 2) + assert.Len(t, cfg.getDialOptions(), 1) +} + +func TestConfig_PluginOptionsAppliedToEachPlugin(t *testing.T) { + t.Parallel() + + applied := make([]string, 0) + cfg := Config{ + PluginOptions: []PluginOption{func(c *PluginConfig) { applied = append(applied, c.Name) }}, + PluginConfigs: []PluginConfig{{Name: "alpha"}, {Name: "beta"}}, + } + + for i := range cfg.PluginConfigs { + for _, opt := range cfg.PluginOptions { + opt(&cfg.PluginConfigs[i]) + } + } + + require.Equal(t, []string{"alpha", "beta"}, applied) +} diff --git a/pkg/catalog/plugin.go b/pkg/catalog/plugin.go index 4343dca..c716a0c 100644 --- a/pkg/catalog/plugin.go +++ b/pkg/catalog/plugin.go @@ -46,6 +46,8 @@ type PluginConfig struct { DataSource DataSource + unaryInterceptors []grpc.UnaryClientInterceptor + YamlConfiguration string LogLevel string @@ -68,6 +70,14 @@ func (c *PluginConfig) IsEnabled() bool { return !c.Disabled } +func (c *PluginConfig) getDialOptions() []grpc.DialOption { + opts := make([]grpc.DialOption, 0, len(c.unaryInterceptors)) + if len(c.unaryInterceptors) > 0 { + opts = append(opts, grpc.WithChainUnaryInterceptor(c.unaryInterceptors...)) + } + return opts +} + type DataSource interface { Load() (string, error) IsDynamic() bool @@ -122,15 +132,19 @@ type pluginImpl struct { func (p *pluginImpl) Close() error { return p.closerGroup.Close() } + func (p *pluginImpl) ClientConnection() grpc.ClientConnInterface { return p.conn } + func (p *pluginImpl) Info() api.Info { return p.info } + func (p *pluginImpl) Logger() *slog.Logger { return p.logger } + func (p *pluginImpl) GrpcServiceNames() []string { return p.grpcServiceNames } @@ -148,7 +162,6 @@ func loadPlugin(ctx context.Context, config PluginConfig) (*pluginImpl, error) { } // Start the plugin client - pluginClient := goplugin.NewClient(&goplugin.ClientConfig{ SecureConfig: seccfg, Logger: slog2hclog.NewWithLevel(config.Logger, config.LogLevel), @@ -161,6 +174,7 @@ func loadPlugin(ctx context.Context, config PluginConfig) (*pluginImpl, error) { Plugins: map[string]goplugin.Plugin{config.Name: &HCRPCPlugin{config: config}}, Cmd: cmd, AllowedProtocols: []goplugin.Protocol{goplugin.ProtocolGRPC}, + GRPCDialOptions: config.getDialOptions(), }) // Connect via RPC @@ -199,7 +213,6 @@ func loadPlugin(ctx context.Context, config PluginConfig) (*pluginImpl, error) { } return newPlugin(ctx, plugin.conn, info, config.Logger, plugin.closers, config.HostServices) - } // injectEnv injects the environment variables into the command