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
15 changes: 13 additions & 2 deletions otdfctl/cmd/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,15 @@ func InitProfile(c *cli.Cli) *profiles.OtdfctlProfileStore {
// instantiates a new handler with authentication via client credentials
// TODO make this a preRun hook
//
// NewHandler resolves the current profile from cli flags, validates
// credentials, and returns a Handler ready for use. Extension points that
// need to inject SDK options based on the resolved profile — for example,
// interceptors that a downstream CLI wants attached to every SDK call — can
// pass one or more handlers.Hook values, which run in order after profile
// resolution and before the underlying SDK is built.
//
//nolint:nestif // separate refactor [https://github.com/opentdf/otdfctl/issues/383]
func NewHandler(c *cli.Cli) handlers.Handler {
func NewHandler(c *cli.Cli, hooks ...handlers.Hook) handlers.Handler {
// if global flags are set then validate and create a temporary profile in memory
var cp *profiles.OtdfctlProfileStore

Expand Down Expand Up @@ -209,7 +216,11 @@ func NewHandler(c *cli.Cli) handlers.Handler {
cli.ExitWithError("Failed to get access token.", err)
}

h, err := handlers.New(handlers.WithProfile(cp))
opts := []handlers.HandlerOption{handlers.WithProfile(cp)}
if len(hooks) > 0 {
opts = append(opts, handlers.WithHook(hooks...))
}
h, err := handlers.New(opts...)
if err != nil {
cli.ExitWithError("Unexpected error", err)
}
Expand Down
101 changes: 96 additions & 5 deletions otdfctl/pkg/handlers/sdk.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,20 +29,58 @@ type handlerOpts struct {
profile *profiles.OtdfctlProfileStore

sdkOpts []sdk.Option

hooks []Hook
}

// HandlerOption configures a Handler during construction. Callers compose
// options by passing them to New; extension points that want to defer their
// SDK-option contribution until profile resolution is complete should use
// WithHook rather than WithSDKOpts.
type HandlerOption func(handlerOpts) handlerOpts

// Hook is the umbrella type for handler-construction hooks. Concrete hook
// variants (PreSDKHook, and any future point-specific hooks added later)
// implement Hook so callers can pass them uniformly through WithHook and
// common.NewHandler. New hook points are added by declaring a new named
// callback type, giving it an isHandlerHook receiver, and extending the
// applyHooks dispatch switch — no new exported registration function is
// needed.
type Hook interface {
isHandlerHook()
}

// PreSDKHookContext exposes the resolved handler configuration to a
// PreSDKHook callback so it can decide which SDK options to contribute
// (for example, an interceptor that only attaches for a specific endpoint
// or profile).
type PreSDKHookContext struct {
Endpoint string
TLSNoVerify bool
Profile *profiles.OtdfctlProfileStore
}

type handlerOptsFunc func(handlerOpts) handlerOpts
// PreSDKHook runs after every HandlerOption has been applied and before
// sdk.New is called. It returns additional SDK options that get appended to
// the final options list. Multiple PreSDKHooks compose in registration
// order and each sees the same fully-resolved PreSDKHookContext.
type PreSDKHook func(PreSDKHookContext) []sdk.Option

func WithEndpoint(endpoint string, tlsNoVerify bool) handlerOptsFunc {
func (PreSDKHook) isHandlerHook() {}

func WithEndpoint(endpoint string, tlsNoVerify bool) HandlerOption {
return func(c handlerOpts) handlerOpts {
c.endpoint = endpoint
c.TLSNoVerify = tlsNoVerify
return c
}
}

func WithProfile(profile *profiles.OtdfctlProfileStore) handlerOptsFunc {
func WithProfile(profile *profiles.OtdfctlProfileStore) HandlerOption {
return func(c handlerOpts) handlerOpts {
if profile == nil {
return c
}
c.profile = profile
c.endpoint = profile.GetEndpoint()
Comment thread
ronelliott marked this conversation as resolved.
c.TLSNoVerify = profile.GetTLSNoVerify()
Expand All @@ -58,20 +96,73 @@ func WithProfile(profile *profiles.OtdfctlProfileStore) handlerOptsFunc {
}
}

func WithSDKOpts(opts ...sdk.Option) handlerOptsFunc {
func WithSDKOpts(opts ...sdk.Option) HandlerOption {
return func(c handlerOpts) handlerOpts {
c.sdkOpts = opts
return c
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

// WithHook registers one or more Hooks that run during handler construction
// after every HandlerOption has been applied and before the SDK is built.
// Nil entries are ignored so a caller cannot accidentally register a hook
// that would panic on execution.
func WithHook(hooks ...Hook) HandlerOption {
return func(c handlerOpts) handlerOpts {
for _, h := range hooks {
if h == nil {
continue
}
c.hooks = append(c.hooks, h)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}
return c
}
}

// applyHooks dispatches every registered Hook to the callback attached to
// its concrete variant. Each variant gets its own context type derived from
// the resolved handler configuration, and any SDK options the hook returns
// are appended to o.sdkOpts. Broken out of New so the extension point is
// directly testable without touching the network. Unknown Hook variants
// are dropped so future variants added upstream do not panic older code
// paths that have not yet been updated to dispatch them.
func applyHooks(o handlerOpts) handlerOpts {
if len(o.hooks) == 0 {
return o
}
for _, h := range o.hooks {
// Switch anticipates future Hook variants (see Hook doc) even though
// only PreSDKHook exists today, so gocritic's single-case suggestion
// would force a rewrite the moment a second variant lands.
//nolint:gocritic // extensible dispatch, keep switch
switch v := h.(type) {
case PreSDKHook:
// A typed-nil function value stored in the Hook interface
// passes the untyped-nil filter inside WithHook, so guard
// per-variant here before invoking the callback.
if v == nil {
continue
}
ctx := PreSDKHookContext{
Endpoint: o.endpoint,
TLSNoVerify: o.TLSNoVerify,
Profile: o.profile,
}
o.sdkOpts = append(o.sdkOpts, v(ctx)...)
}
}
return o
}

// Creates a new handler wrapping the SDK, which is authenticated through the cached client-credentials flow tokens
func New(opts ...handlerOptsFunc) (Handler, error) {
func New(opts ...HandlerOption) (Handler, error) {
var o handlerOpts
for _, f := range opts {
o = f(o)
}

o = applyHooks(o)

u, err := utils.NormalizeEndpoint(o.endpoint)
if err != nil {
return Handler{}, err
Expand Down
163 changes: 163 additions & 0 deletions otdfctl/pkg/handlers/sdk_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
package handlers

import (
"testing"

"github.com/opentdf/platform/sdk"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestWithHook_RegistersInOrder(t *testing.T) {
var invoked []string

hookA := PreSDKHook(func(PreSDKHookContext) []sdk.Option {
invoked = append(invoked, "a")
return nil
})
hookB := PreSDKHook(func(PreSDKHookContext) []sdk.Option {
invoked = append(invoked, "b")
return nil
})

var o handlerOpts
o = WithHook(hookA)(o)
o = WithHook(hookB)(o)

require.Len(t, o.hooks, 2, "expected both hooks registered")

applyHooks(o)
assert.Equal(t, []string{"a", "b"}, invoked, "hooks should execute in registration order")
}

func TestWithHook_VariadicRegistersAllInOrder(t *testing.T) {
var invoked []string

hookA := PreSDKHook(func(PreSDKHookContext) []sdk.Option {
invoked = append(invoked, "a")
return nil
})
hookB := PreSDKHook(func(PreSDKHookContext) []sdk.Option {
invoked = append(invoked, "b")
return nil
})

var o handlerOpts
o = WithHook(hookA, hookB)(o)

require.Len(t, o.hooks, 2, "expected both hooks registered")

applyHooks(o)
assert.Equal(t, []string{"a", "b"}, invoked)
}

func TestApplyHooks_PreSDKHookReceivesResolvedContext(t *testing.T) {
var captured PreSDKHookContext

o := handlerOpts{
endpoint: "https://platform.example.test",
TLSNoVerify: true,
}
o = WithHook(PreSDKHook(func(ctx PreSDKHookContext) []sdk.Option {
captured = ctx
return nil
}))(o)

_ = applyHooks(o)

assert.Equal(t, "https://platform.example.test", captured.Endpoint)
assert.True(t, captured.TLSNoVerify)
assert.Nil(t, captured.Profile, "no profile was set on the handlerOpts")
}

func TestApplyHooks_AppendsReturnedOptionsInOrder(t *testing.T) {
optA := sdk.WithConnectionValidation()
optB := sdk.WithInsecurePlaintextConn()

var o handlerOpts
o = WithHook(PreSDKHook(func(PreSDKHookContext) []sdk.Option { return []sdk.Option{optA} }))(o)
o = WithHook(PreSDKHook(func(PreSDKHookContext) []sdk.Option { return []sdk.Option{optB} }))(o)

o = applyHooks(o)

require.Len(t, o.sdkOpts, 2, "expected one option per hook")
}

func TestApplyHooks_NoopWhenNoHooks(t *testing.T) {
baseline := sdk.WithConnectionValidation()
o := handlerOpts{sdkOpts: []sdk.Option{baseline}}

o = applyHooks(o)

assert.Len(t, o.sdkOpts, 1, "applyHooks must not mutate sdkOpts when no hooks are registered")
}

// TestWithHook_NilHookIsSkipped guards against a nil Hook slipping into the
// registered list and panicking when applyHooks invokes it.
func TestWithHook_NilHookIsSkipped(t *testing.T) {
var o handlerOpts
o = WithHook(nil)(o)

assert.Empty(t, o.hooks, "nil hook must not be registered")
}

// TestWithHook_NilAmongVariadicHooksIsSkipped confirms the nil guard applies
// per element when WithHook is called with a mixed variadic list.
func TestWithHook_NilAmongVariadicHooksIsSkipped(t *testing.T) {
realHook := PreSDKHook(func(PreSDKHookContext) []sdk.Option { return nil })

var o handlerOpts
o = WithHook(nil, realHook, nil)(o)

require.Len(t, o.hooks, 1, "only the non-nil hook should be registered")
}

// TestWithProfile_NilProfileIsSkipped guards against a nil profile
// dereferencing on the immediately following GetEndpoint / GetTLSNoVerify
// calls.
func TestWithProfile_NilProfileIsSkipped(t *testing.T) {
var o handlerOpts

assert.NotPanics(t, func() {
o = WithProfile(nil)(o)
})

assert.Nil(t, o.profile, "nil profile must not be stored")
assert.Empty(t, o.endpoint, "endpoint must remain unset when profile is nil")
}

// TestApplyHooks_TypedNilPreSDKHookIsDropped guards against the interface
// footgun where a typed-nil function value wrapped in the Hook interface
// passes the untyped-nil check in WithHook and would otherwise panic on
// invocation. The dispatch switch drops it per-variant.
func TestApplyHooks_TypedNilPreSDKHookIsDropped(t *testing.T) {
var typedNil PreSDKHook

var o handlerOpts
o = WithHook(typedNil)(o)

require.Len(t, o.hooks, 1, "typed-nil interface value bypasses the untyped-nil filter, so it lands in the hooks slice")

assert.NotPanics(t, func() {
o = applyHooks(o)
})
assert.Empty(t, o.sdkOpts, "typed-nil PreSDKHook must not contribute SDK options")
}

// unknownHook is a Hook variant applyHooks does not recognize. It exists to
// make sure the dispatch switch drops unknown variants instead of panicking,
// which is what lets future hook points land in later PRs without breaking
// existing binaries.
type unknownHook struct{}

func (unknownHook) isHandlerHook() {}

func TestApplyHooks_UnknownHookVariantIsDropped(t *testing.T) {
var o handlerOpts
o.hooks = append(o.hooks, unknownHook{})

assert.NotPanics(t, func() {
o = applyHooks(o)
})
assert.Empty(t, o.sdkOpts, "unknown hook variants must not contribute SDK options")
}
Loading