ory/hydra · error

failed to encode JSON Web Key Set

Error message

failed to encode JSON Web Key Set

What it means

OnlyPublicSDKKeys converts a set of Hydra JSON Web Keys to their public form by round-tripping them through encoding/json. This first-wrap error occurs when json.Encoder fails to serialize the incoming []hydra.JsonWebKey set — practically never happens for valid keys since JsonWebKey is JSON-marshalable, but the library wraps it defensively.

Source

Thrown at cmd/jwk_sdk.go:23

import (
	"bytes"
	"encoding/json"

	jose "github.com/go-jose/go-jose/v3"
	"github.com/pkg/errors"

	hydra "github.com/ory/hydra-client-go/v2"
)

// OnlyPublicSDKKeys strips the private parts from a key set so that it is safe
// to print.
func OnlyPublicSDKKeys(in []hydra.JsonWebKey) (out []hydra.JsonWebKey, _ error) {
	var interim []jose.JSONWebKey
	var b bytes.Buffer

	if err := json.NewEncoder(&b).Encode(&in); err != nil {
		return nil, errors.Wrap(err, "failed to encode JSON Web Key Set")
	}

	if err := json.NewDecoder(&b).Decode(&interim); err != nil {
		return nil, errors.Wrap(err, "failed to decode JSON Web Key Set")
	}

	for i, key := range interim {
		interim[i] = key.Public()
	}

	b.Reset()
	if err := json.NewEncoder(&b).Encode(&interim); err != nil {
		return nil, errors.Wrap(err, "failed to encode JSON Web Key Set")
	}

	var keys []hydra.JsonWebKey
	if err := json.NewDecoder(&b).Decode(&keys); err != nil {
		return nil, errors.Wrap(err, "failed to decode JSON Web Key Set")

View on GitHub (pinned to 4174065ffb)

Solutions

  1. Ensure the []hydra.JsonWebKey input comes from the hydra JWK admin/API response (jose.JSONWebKeySet), not hand-built structs.
  2. Test-encode one key with json.Marshal(key) to find the offending key and inspect its fields.
  3. Filter out malformed keys before calling OnlyPublicSDKKeys.

Example fix

// before
out, err := OnlyPublicSDKKeys(handBuiltKeys) // corrupt key -> encode fails

// after
valid := keys[:0]
for _, k := range keys {
    if _, err := json.Marshal(k); err == nil {
        valid = append(valid, k)
    }
}
out, err := OnlyPublicSDKKeys(valid)
Defensive patterns

Strategy: validation

Validate before calling

for _, k := range in {
    if _, err := json.Marshal(k); err != nil {
        return fmt.Errorf("key %q is not JSON-marshalable: %w", k.Kid, err)
    }
}

Type guard

func isMarshalableJWK(k hydra.JsonWebKey) bool {
    b, err := json.Marshal(k)
    return err == nil && len(b) > 0
}

Try / catch

out, err := OnlyPublicSDKKeys(keys)
if err != nil {
    return nil, fmt.Errorf("converting SDK keys failed: %+v", err) // %+v reveals wrapped json cause
}

Prevention

When it happens

Trigger: Calling OnlyPublicSDKKeys with a []hydra.JsonWebKey whose contents cannot be JSON-encoded — e.g. keys containing unsupported values that the jose-backed JsonWebKey marshals to invalid JSON (rare; corrupt or programmatically-constructed key structs).

Common situations: Passing keys constructed manually with non-serializable fields instead of keys obtained from hydra's JWK API; a JsonWebKey carrying exotic (e.g. NaN float or channel-backed custom marshaling) data from an interceptor.

Understand the failure class

Background: "JSON serialization failed", "not JSON serializable", "Failed to serialize": why JSON marshaling errors happen and how to fix them — this error's family across 46 libraries.

Related errors


AI-assisted analysis of ory/hydra@4174065ffb (2026-09-03). Data as JSON: /api/errors/d495b463d411d87e. Report an issue: GitHub.