Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions sdk/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ toolchain go1.25.8

require (
connectrpc.com/connect v1.19.1
connectrpc.com/grpchealth v1.4.0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit (non-blocking): You already flagged this in the PR description — grpchealth is test-only but Go modules can't express that, so this promotes it to a direct dep in sdk/go.mod for all downstream consumers.

Can we move newHealthTestServer into sdk/internal/healthtest/ with its own go.mod? That keeps grpchealth out of the SDK's public dependency surface. Fine as a follow-up commit on this PR or a separate PR — no need to block on it.

github.com/Masterminds/semver/v3 v3.4.0
github.com/google/uuid v1.6.0
github.com/gowebpki/jcs v1.0.1
Expand Down
2 changes: 2 additions & 0 deletions sdk/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.6-2025060316535
buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.6-20250603165357-b52ab10f4468.1/go.mod h1:avRlCjnFzl98VPaeCtJ24RrV/wwHFzB8sWXhj26+n/U=
connectrpc.com/connect v1.19.1 h1:R5M57z05+90EfEvCY1b7hBxDVOUl45PrtXtAV2fOC14=
connectrpc.com/connect v1.19.1/go.mod h1:tN20fjdGlewnSFeZxLKb0xwIZ6ozc3OQs2hTXy4du9w=
connectrpc.com/grpchealth v1.4.0 h1:MJC96JLelARPgZTiRF9KRfY/2N9OcoQvF2EWX07v2IE=
connectrpc.com/grpchealth v1.4.0/go.mod h1:WhW6m1EzTmq3Ky1FE8EfkIpSDc6TfUx2M2KqZO3ts/Q=
github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=
github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
Expand Down
5 changes: 4 additions & 1 deletion sdk/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,10 @@ func WithPlatformConfiguration(platformConfiguration PlatformConfiguration) Opti
}
}

// WithConnectionValidation will validate connection to a healthy, running platform
// WithConnectionValidation will validate connection to a healthy, running platform at
// SDK construction time. For runtime readiness probes (e.g. Kubernetes liveness/readiness
// endpoints), use SDK.HealthCheck(ctx, service) instead — it honors ctx for deadlines
// and tracing and does not fail-fast at construction.
func WithConnectionValidation() Option {
return func(c *config) {
c.shouldValidatePlatformConnectivity = true
Expand Down
124 changes: 112 additions & 12 deletions sdk/sdk.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,12 @@ import (
const (
// Failure while connecting to a service.
// Check your configuration and/or retry.
ErrGrpcDialFailed = Error("failed to dial grpc endpoint")
ErrShutdownFailed = Error("failed to shutdown sdk")
ErrPlatformUnreachable = Error("platform unreachable or not responding")
ErrGrpcDialFailed = Error("failed to dial grpc endpoint")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: alignment inconsistency

ErrShutdownFailed = Error("failed to shutdown sdk")
ErrPlatformUnreachable = Error("platform unreachable or not responding")
// ErrHealthCheckUnsupported is returned by SDK.HealthCheck when the SDK is configured
// in IPC mode, which does not support the gRPC Health protocol.
ErrHealthCheckUnsupported = Error("health check not supported in IPC mode")
ErrPlatformConfigFailed = Error("failed to retrieve platform configuration")
ErrPlatformEndpointMalformed = Error("platform endpoint is malformed")
ErrPlatformIssuerNotFound = Error("issuer not found in well-known idp configuration")
Expand All @@ -58,6 +61,33 @@ func (c Error) Error() string {
return string(c)
}

// HealthStatus is the serving status reported by the platform's gRPC Health v1 endpoint.
// It mirrors google.golang.org/grpc/health/grpc_health_v1.HealthCheckResponse_ServingStatus
// so callers do not need to import the grpc health protobuf to branch on results.
type HealthStatus int

const (
// HealthStatusUnknown means the platform could not determine status, or the requested
// service is not registered on this deployment.
HealthStatusUnknown HealthStatus = iota
// HealthStatusServing means the requested scope reports SERVING.
HealthStatusServing
// HealthStatusNotServing means the requested scope was reached but reports NOT_SERVING.
HealthStatusNotServing
)

// String returns the uppercase name of the status. Unknown or out-of-range values render as "UNKNOWN".
func (s HealthStatus) String() string {
switch s { //nolint:exhaustive // default intentionally covers HealthStatusUnknown and any future out-of-range values
case HealthStatusServing:
return "SERVING"
case HealthStatusNotServing:
return "NOT_SERVING"
default:
return "UNKNOWN"
}
}

// getLogger returns the package-level logger, defaulting to slog.Default() if not set to
// provide access to the logger in exported functions where signatures are unable to be altered
func getLogger() *slog.Logger {
Expand Down Expand Up @@ -310,6 +340,57 @@ func (s SDK) Conn() *ConnectRPCConnection {
return s.conn
}

// HealthCheck queries the platform's gRPC Health v1 endpoint (grpc.health.v1.Health/Check)
// and returns the reported serving status.
//
// The service argument selects the check scope:
//
// - "" — reachability check. Returns SERVING if the health handler responds. Does
// not exercise any registered readiness probe.
// - "all" — runs every readiness check the platform has registered. Returns
// NOT_SERVING if any registered service reports an error.
// - other — runs only the named service's readiness check (e.g. "kas", "authorization").
// Returns HealthStatusUnknown if the service is not registered on this deployment.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The valid values for service ("", "all", "kas", "authorization", etc.) are documented here but there are no constants for them. Consider exported constants like HealthServiceAll = "all" (even just for "all" and "") for discoverability since this is a public SDK API.

(Or at minimum, a note in the README/docs listing the known service names)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pflynn-virtru Any reason not to just simplify this to IsHealthy(ctx context.Context) or something like IsReachable(ctx context.Context). If we don't want to simplify this we need expose const like @marythought proposed above imo.

//
// The call honors ctx for deadline, cancellation, and trace-context propagation. Callers are
// expected to manage timeouts via context.WithTimeout and to drive probe cadence / retry themselves.
//
// OTEL tracing works automatically when the caller has registered otelconnect.NewInterceptor()
// via sdk.WithExtraClientOptions at SDK construction time. The SDK does not emit spans of its own.
//
// Returns (HealthStatusServing, nil) on SERVING; (HealthStatusNotServing, nil) on NOT_SERVING;
// (HealthStatusUnknown, nil) on UNKNOWN / SERVICE_UNKNOWN; (HealthStatusUnknown, err wrapping
// ErrPlatformUnreachable) on any transport failure including ctx errors; and
// (HealthStatusUnknown, ErrHealthCheckUnsupported) when the SDK is in IPC mode.
func (s SDK) HealthCheck(ctx context.Context, service string) (HealthStatus, error) {
if s.ipc || s.conn == nil {
return HealthStatusUnknown, ErrHealthCheckUnsupported
}
status, err := checkPlatformHealth(ctx, s.conn.Endpoint, service, s.conn.Client, s.conn.Options)
if err != nil {
// Unregistered services can surface in two ways depending on the server
// implementation. The OpenTDF platform's handler reports them via proto
// HealthCheckResponse_UNKNOWN, which falls through to the switch default
// below. Generic grpchealth servers (e.g. grpchealth.NewStaticChecker,
// which the SDK tests use) surface them as a Connect not_found error.
// Both paths map to HealthStatusUnknown with no transport-error wrapper.
var connErr *connect.Error
if errors.As(err, &connErr) && connErr.Code() == connect.CodeNotFound {
return HealthStatusUnknown, nil
}
return HealthStatusUnknown, errors.Join(ErrPlatformUnreachable, err)
}
switch status { //nolint:exhaustive // default intentionally covers UNKNOWN and SERVICE_UNKNOWN
case healthpb.HealthCheckResponse_SERVING:
return HealthStatusServing, nil
case healthpb.HealthCheckResponse_NOT_SERVING:
return HealthStatusNotServing, nil
default:
// UNKNOWN and SERVICE_UNKNOWN both map to HealthStatusUnknown.
return HealthStatusUnknown, nil
}
}

type TdfType string

const (
Expand Down Expand Up @@ -413,21 +494,40 @@ func isValidManifest(manifest string, intensity SchemaValidationIntensity) (bool
return true, nil
}

// Test connectability to the platform and validate a healthy status
func validateHealthyPlatformConnection(platformEndpoint string, httpClient *http.Client, options []connect.ClientOption) error {
// checkPlatformHealth issues a single gRPC Health v1 Check against the platform health endpoint.
// ctx controls deadline, cancellation, and trace-context propagation. service selects scope:
// "" = reachability, "all" = every registered readiness probe, otherwise a specific service name.
func checkPlatformHealth(
ctx context.Context,
endpoint, service string,
httpClient *http.Client,
options []connect.ClientOption,
) (healthpb.HealthCheckResponse_ServingStatus, error) {
healthClient := connect.NewClient[healthpb.HealthCheckRequest, healthpb.HealthCheckResponse](
httpClient,
platformEndpoint+"/grpc.health.v1.Health/Check",
endpoint+"/grpc.health.v1.Health/Check",
Comment thread
pflynn-virtru marked this conversation as resolved.
Resolved
options...,
)
res, err := healthClient.CallUnary(
context.Background(),
connect.NewRequest(&healthpb.HealthCheckRequest{}),
)
if err != nil || res.Msg.GetStatus() != healthpb.HealthCheckResponse_SERVING {
return errors.Join(ErrPlatformUnreachable, err)
res, err := healthClient.CallUnary(ctx, connect.NewRequest(&healthpb.HealthCheckRequest{Service: service}))
if err != nil {
return healthpb.HealthCheckResponse_UNKNOWN, err
}
return res.Msg.GetStatus(), nil
}

// validateHealthyPlatformConnection is the construction-time reachability gate used by New when
// WithConnectionValidation is set. It uses context.Background() to preserve today's behavior.
// Callers pass cfg.extraClientOptions (pre-auth) because the auth and audit interceptors are
// assembled after this gate fires; the runtime SDK.HealthCheck method uses the post-interceptor
// s.conn.Options instead.
func validateHealthyPlatformConnection(platformEndpoint string, httpClient *http.Client, options []connect.ClientOption) error {
status, err := checkPlatformHealth(context.Background(), platformEndpoint, "", httpClient, options)
if err != nil {
return errors.Join(ErrPlatformUnreachable, err)
}
if status != healthpb.HealthCheckResponse_SERVING {
return errors.Join(ErrPlatformUnreachable, fmt.Errorf("platform health status %q", status))
}
return nil
}

Expand Down
170 changes: 170 additions & 0 deletions sdk/sdk_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,15 @@ package sdk_test

import (
"bytes"
"context"
"encoding/base64"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"time"

"connectrpc.com/grpchealth"
"github.com/opentdf/platform/protocol/go/policy/attributes/attributesconnect"
"github.com/opentdf/platform/protocol/go/policy/kasregistry/kasregistryconnect"
"github.com/opentdf/platform/protocol/go/policy/resourcemapping/resourcemappingconnect"
Expand Down Expand Up @@ -313,3 +318,168 @@ func Test_GetType_Invalid2Bytes(t *testing.T) {

assert.Equal(t, sdk.Invalid, tdfType)
}

func TestHealthStatus_String(t *testing.T) {
tests := []struct {
name string
status sdk.HealthStatus
want string
}{
{"unknown", sdk.HealthStatusUnknown, "UNKNOWN"},
{"serving", sdk.HealthStatusServing, "SERVING"},
{"not_serving", sdk.HealthStatusNotServing, "NOT_SERVING"},
{"out_of_range", sdk.HealthStatus(99), "UNKNOWN"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.want, tt.status.String())
})
}
}

func TestErrHealthCheckUnsupported_Distinct(t *testing.T) {
assert.NotEqual(t, sdk.ErrHealthCheckUnsupported, sdk.ErrPlatformUnreachable)
assert.Equal(t, "health check not supported in IPC mode", sdk.ErrHealthCheckUnsupported.Error())
}

// newHealthTestServer starts an httptest.Server serving grpc.health.v1.Health.
// serving is the set of service names that should report SERVING; notServing is the set
// that should report NOT_SERVING. Any service name not in either set causes
// grpchealth.StaticChecker to return a Connect not_found error, which SDK.HealthCheck
// maps to HealthStatusUnknown.
// The empty service name ("") reports SERVING regardless (StaticChecker default).
func newHealthTestServer(t *testing.T, serving, notServing []string) *httptest.Server {
t.Helper()
all := append([]string{}, serving...)
all = append(all, notServing...)
checker := grpchealth.NewStaticChecker(all...)
for _, svc := range notServing {
checker.SetStatus(svc, grpchealth.StatusNotServing)
}
mux := http.NewServeMux()
path, handler := grpchealth.NewHandler(checker)
mux.Handle(path, handler)
return httptest.NewServer(mux)
}

func TestSDK_HealthCheck_IPCMode_ReturnsErrHealthCheckUnsupported(t *testing.T) {
// IPC mode requires a coreConn; provide a dummy one to satisfy sdk.New.
dummyConn := &sdk.ConnectRPCConnection{
Endpoint: "http://localhost:0",
Client: http.DefaultClient,
}
s, err := sdk.New("",
sdk.WithIPC(),
sdk.WithCustomCoreConnection(dummyConn),
sdk.WithPlatformConfiguration(sdk.PlatformConfiguration{
"idp": map[string]interface{}{
"issuer": "https://example.org",
"authorization_endpoint": "https://example.org/auth",
"token_endpoint": "https://example.org/token",
},
}),
)
require.NoError(t, err)
require.NotNil(t, s)

ctx := context.Background()
status, err := s.HealthCheck(ctx, "")
assert.Equal(t, sdk.HealthStatusUnknown, status)
require.ErrorIs(t, err, sdk.ErrHealthCheckUnsupported)
}

func TestSDK_HealthCheck_Unreachable_ReturnsErrPlatformUnreachable(t *testing.T) {
s, err := sdk.New(badPlatformEndpoint,
sdk.WithPlatformConfiguration(sdk.PlatformConfiguration{
"idp": map[string]interface{}{
"issuer": "https://example.org",
"authorization_endpoint": "https://example.org/auth",
"token_endpoint": "https://example.org/token",
},
}),
)
require.NoError(t, err)
require.NotNil(t, s)

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

start := time.Now()
status, err := s.HealthCheck(ctx, "")
elapsed := time.Since(start)

assert.Equal(t, sdk.HealthStatusUnknown, status)
require.ErrorIs(t, err, sdk.ErrPlatformUnreachable)
assert.Less(t, elapsed, 2*time.Second, "health check should return promptly against a closed port, not wait for the ctx deadline")
}

func TestSDK_HealthCheck_ContextCanceled_ReturnsQuickly(t *testing.T) {
s, err := sdk.New(badPlatformEndpoint,
sdk.WithPlatformConfiguration(sdk.PlatformConfiguration{
"idp": map[string]interface{}{
"issuer": "https://example.org",
"authorization_endpoint": "https://example.org/auth",
"token_endpoint": "https://example.org/token",
},
}),
)
require.NoError(t, err)
require.NotNil(t, s)

ctx, cancel := context.WithCancel(context.Background())
cancel() // canceled before the call

start := time.Now()
status, err := s.HealthCheck(ctx, "")
elapsed := time.Since(start)

assert.Equal(t, sdk.HealthStatusUnknown, status)
require.Error(t, err)
require.ErrorIs(t, err, sdk.ErrPlatformUnreachable)
require.ErrorIs(t, err, context.Canceled)
assert.Less(t, elapsed, 500*time.Millisecond, "pre-canceled ctx should short-circuit")
Comment thread
pflynn-virtru marked this conversation as resolved.
Resolved
}

func TestSDK_HealthCheck_Serving_HappyPath(t *testing.T) {
ts := newHealthTestServer(t, []string{"kas"}, []string{"broken"})
defer ts.Close()

s, err := sdk.New(ts.URL,
sdk.WithPlatformConfiguration(sdk.PlatformConfiguration{
"idp": map[string]interface{}{
"issuer": "https://example.org",
"authorization_endpoint": "https://example.org/auth",
"token_endpoint": "https://example.org/token",
},
}),
)
require.NoError(t, err)
require.NotNil(t, s)

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

t.Run("empty service returns SERVING", func(t *testing.T) {
status, err := s.HealthCheck(ctx, "")
require.NoError(t, err)
assert.Equal(t, sdk.HealthStatusServing, status)
})

t.Run("named serving service returns SERVING", func(t *testing.T) {
status, err := s.HealthCheck(ctx, "kas")
require.NoError(t, err)
assert.Equal(t, sdk.HealthStatusServing, status)
})

t.Run("named not-serving service returns NOT_SERVING", func(t *testing.T) {
status, err := s.HealthCheck(ctx, "broken")
require.NoError(t, err)
assert.Equal(t, sdk.HealthStatusNotServing, status)
})

t.Run("unknown service returns UNKNOWN", func(t *testing.T) {
status, err := s.HealthCheck(ctx, "does-not-exist")
require.NoError(t, err)
assert.Equal(t, sdk.HealthStatusUnknown, status)
})
}
Loading