Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions pkg/catalog/catalog.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
8 changes: 8 additions & 0 deletions pkg/catalog/catalog_model.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
59 changes: 59 additions & 0 deletions pkg/catalog/catalog_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
32 changes: 32 additions & 0 deletions pkg/catalog/options.go
Original file line number Diff line number Diff line change
@@ -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
})
}
}
85 changes: 85 additions & 0 deletions pkg/catalog/options_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
17 changes: 15 additions & 2 deletions pkg/catalog/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ type PluginConfig struct {

DataSource DataSource

unaryInterceptors []grpc.UnaryClientInterceptor

YamlConfiguration string

LogLevel string
Expand All @@ -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
Expand Down Expand Up @@ -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
}
Expand All @@ -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),
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading