Skip to content

Commit

Permalink
feat: add flag to export public keys
Browse files Browse the repository at this point in the history
  • Loading branch information
aeneasr committed Dec 27, 2023
1 parent f9cee32 commit 0685dac
Show file tree
Hide file tree
Showing 6 changed files with 105 additions and 5 deletions.
12 changes: 11 additions & 1 deletion cmd/cmd_create_jwks.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ package cmd
import (
"context"

"github.com/ory/hydra/v2/jwk"

"github.com/spf13/cobra"

hydra "github.com/ory/hydra-client-go/v2"
Expand Down Expand Up @@ -46,12 +48,20 @@ func NewCreateJWKSCmd() *cobra.Command {
return cmdx.PrintOpenAPIError(cmd, err)
}

if flagx.MustGetBool(cmd, "public") {
jwks.Keys, err = jwk.OnlyPublicSDKKeys(jwks.Keys)
if err != nil {
return err
}
}

cmdx.PrintTable(cmd, &outputJSONWebKeyCollection{Keys: jwks.Keys, Set: args[0]})
return nil
},
}
cmd.Root().Name()

cmd.Flags().String(alg, "RS256", "The algorithm to be used to generated they key. Supports: RS256, RS512, ES256, ES512, EdDSA")
cmd.Flags().String(use, "sig", "The intended use of this key. Supports: sig, enc")
cmd.Flags().Bool("public", false, "Only return public keys")
return cmd
}
8 changes: 8 additions & 0 deletions cmd/cmd_create_jwks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,12 @@ func TestCreateJWKS(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, expected.Keys[0].KeyID, actual.Get("keys.0.kid").String())
})

t.Run("case=gets jwks public", func(t *testing.T) {
set := uuid.Must(uuid.NewV4()).String()
actual := gjson.Parse(cmdx.ExecNoErr(t, c, set, "--use", "enc", "--alg", "RS256", "--public"))

assert.NotEmptyf(t, actual.Get("keys.0.kid").String(), "Expected kid to be set but got: %s", actual.Raw)
assert.Empty(t, actual.Get("keys.0.p").String(), "public key should not contain private key components: %s", actual.Raw)
})
}
23 changes: 20 additions & 3 deletions cmd/cmd_get_jwks.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,28 @@ package cmd
import (
"github.com/spf13/cobra"

"github.com/ory/hydra/v2/jwk"
"github.com/ory/x/flagx"

"github.com/ory/hydra/v2/cmd/cliclient"
"github.com/ory/x/cmdx"
)

func NewGetJWKSCmd() *cobra.Command {
return &cobra.Command{
cmd := &cobra.Command{
Use: "jwk set-1 [set-2] ...",
Aliases: []string{"jwks"},
Args: cobra.MinimumNArgs(1),
Short: "Get one or more JSON Web Key Set by its ID(s)",
Long: `This command gets all the details about an JSON Web Key. You can use this command in combination with jq.`,
Example: `To get the JSON Web Key Set's secret, run:
Example: `To get the JSON Web Key Set's use, run:
{{ .CommandPath }} <set-id> | jq -r '.[].use'
{{ .CommandPath }} <set-id> | jq -r '.[].use'`,
To get the JSON Web Key Set as only public keys:
{{ .CommandPath }} --public <set-id>'
`,
RunE: func(cmd *cobra.Command, args []string) error {
m, _, err := cliclient.NewClient(cmd)
if err != nil {
Expand All @@ -36,6 +44,13 @@ func NewGetJWKSCmd() *cobra.Command {
sets.Keys = append(sets.Keys, key.Keys...)
}

if flagx.MustGetBool(cmd, "public") {
sets.Keys, err = jwk.OnlyPublicSDKKeys(sets.Keys)
if err != nil {
return err
}
}

if len(sets.Keys) == 1 {
cmdx.PrintRow(cmd, outputJsonWebKey{Set: args[0], JsonWebKey: sets.Keys[0]})
} else if len(sets.Keys) > 1 {
Expand All @@ -45,4 +60,6 @@ func NewGetJWKSCmd() *cobra.Command {
return nil
},
}
cmd.Flags().Bool("public", false, "Only return public keys")
return cmd
}
14 changes: 13 additions & 1 deletion cmd/cmd_get_jwks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
"github.com/ory/x/cmdx"
)

func TestGetJwks(t *testing.T) {
func TestGetJWKS(t *testing.T) {
ctx := context.Background()
c := cmd.NewGetJWKSCmd()
reg := setup(t, c)
Expand All @@ -34,4 +34,16 @@ func TestGetJwks(t *testing.T) {

assert.Equal(t, expected.Keys[0].KeyID, actual.Get("kid").String())
})

t.Run("case=gets jwks public", func(t *testing.T) {
actual := gjson.Parse(cmdx.ExecNoErr(t, c, set, "--public"))

expected, err := reg.KeyManager().GetKeySet(ctx, set)
require.NoError(t, err)

assert.Equal(t, expected.Keys[0].KeyID, actual.Get("kid").String())

assert.NotEmptyf(t, actual.Get("kid").String(), "Expected kid to be set but got: %s", actual.Raw)
assert.Empty(t, actual.Get("p").String(), "public key should not contain private key components: %s", actual.Raw)
})
}
33 changes: 33 additions & 0 deletions jwk/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@
package jwk

import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"sync"

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

"github.com/ory/x/josex"

"github.com/ory/x/errorsx"
Expand Down Expand Up @@ -149,3 +153,32 @@ func PEMBlockForKey(key interface{}) (*pem.Block, error) {
return nil, errors.New("Invalid key type")
}
}

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 encode 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 encode JSON Web Key Set")
}

return keys, nil
}
20 changes: 20 additions & 0 deletions jwk/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,14 @@ import (
"crypto/ed25519"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"io"
"strings"
"testing"

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

"github.com/go-jose/go-jose/v3"
"github.com/go-jose/go-jose/v3/cryptosigner"
"github.com/golang/mock/gomock"
Expand Down Expand Up @@ -267,3 +270,20 @@ func TestGetOrGenerateKeys(t *testing.T) {
assert.EqualError(t, err, "key not found")
})
}

func TestOnlyPublicSDKKeys(t *testing.T) {
set, err := jwk.GenerateJWK(context.Background(), jose.RS256, "test-id-1", "sig")
require.NoError(t, err)

out, err := json.Marshal(set)
require.NoError(t, err)

var sdkSet hydra.JsonWebKeySet
require.NoError(t, json.Unmarshal(out, &sdkSet))

assert.NotEmpty(t, sdkSet.Keys[0].P)
result, err := jwk.OnlyPublicSDKKeys(&sdkSet)

Check failure on line 285 in jwk/helper_test.go

View workflow job for this annotation

GitHub Actions / Run HSM tests

cannot use &sdkSet (value of type *openapi.JsonWebKeySet) as []openapi.JsonWebKey value in argument to jwk.OnlyPublicSDKKeys

Check failure on line 285 in jwk/helper_test.go

View workflow job for this annotation

GitHub Actions / Run tests and lints

cannot use &sdkSet (value of type *openapi.JsonWebKeySet) as []openapi.JsonWebKey value in argument to jwk.OnlyPublicSDKKeys
require.NoError(t, err)

assert.Empty(t, result.Keys[0].P)

Check failure on line 288 in jwk/helper_test.go

View workflow job for this annotation

GitHub Actions / Run HSM tests

result.Keys undefined (type []openapi.JsonWebKey has no field or method Keys)

Check failure on line 288 in jwk/helper_test.go

View workflow job for this annotation

GitHub Actions / Run tests and lints

result.Keys undefined (type []openapi.JsonWebKey has no field or method Keys)
}

0 comments on commit 0685dac

Please sign in to comment.