Skip to content

Commit

Permalink
OAuth2 JWT bearer grant type and JWT client auth
Browse files Browse the repository at this point in the history
Allow OPA to issue JWT's which it uses to authenticate a configured
OAuth2 client, as described in RFC7523. This replaces the client_secret
as the actual credential and allows for either using an entirely new
grant type called "JWT bearer", or using the previously supported
client_credentials grant type, only with the client_secret replaced
by a signed JWT. This change covers both scenarios described in
RFC7523.

Other changes made to accomodate this feature:

- Add `private_key` attribute to keys struct to allow for both public and
private keys to be stored there.
- Refactored the keys configuration struct and logic to its
own package no longer coupled to bundles.

Closes #3055

Signed-off-by: Anders Eknert <[email protected]>
  • Loading branch information
anderseknert committed Jan 20, 2021
1 parent 2d4f7c0 commit 36ba445
Show file tree
Hide file tree
Showing 22 changed files with 1,059 additions and 346 deletions.
77 changes: 5 additions & 72 deletions bundle/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@
package bundle

import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"reflect"

"github.com/open-policy-agent/opa/internal/jwx/jwa"
"github.com/open-policy-agent/opa/internal/jwx/jws/sign"
"github.com/open-policy-agent/opa/keys"

"github.com/open-policy-agent/opa/util"
)
Expand All @@ -22,6 +21,10 @@ const (
defaultTokenSigningAlg = "RS256"
)

// KeyConfig holds the keys used to sign or verify bundles and tokens
// Moved to own package, alias kept for backwards compatibility
type KeyConfig = keys.Config

// VerificationConfig represents the key configuration used to verify a signed bundle
type VerificationConfig struct {
PublicKeys map[string]*KeyConfig
Expand Down Expand Up @@ -71,76 +74,6 @@ func (vc *VerificationConfig) GetPublicKey(id string) (*KeyConfig, error) {
return kc, nil
}

// KeyConfig holds the actual public keys used to verify a signed bundle
type KeyConfig struct {
Key string `json:"key"`
Algorithm string `json:"algorithm"`
Scope string `json:"scope"`
}

// NewKeyConfig return a new KeyConfig
func NewKeyConfig(key, alg, scope string) (*KeyConfig, error) {
var pubKey string
if _, err := os.Stat(key); err == nil {
bs, err := ioutil.ReadFile(key)
if err != nil {
return nil, err
}
pubKey = string(bs)
} else if os.IsNotExist(err) {
pubKey = key
} else {
return nil, err
}

return &KeyConfig{
Key: pubKey,
Algorithm: alg,
Scope: scope,
}, nil
}

// ParseKeysConfig returns a map containing the public key and the signing algorithm
func ParseKeysConfig(raw json.RawMessage) (map[string]*KeyConfig, error) {
keys := map[string]*KeyConfig{}
var obj map[string]json.RawMessage

if err := util.Unmarshal(raw, &obj); err == nil {
for k := range obj {
var keyConfig KeyConfig
if err = util.Unmarshal(obj[k], &keyConfig); err != nil {
return nil, err
}

if err = keyConfig.validateAndInjectDefaults(k); err != nil {
return nil, err
}

keys[k] = &keyConfig
}
} else {
return nil, err
}
return keys, nil
}

func (k *KeyConfig) validateAndInjectDefaults(id string) error {
if k.Key == "" {
return fmt.Errorf("invalid keys configuration: verification key empty for key ID %v", id)
}

if k.Algorithm == "" {
k.Algorithm = defaultTokenSigningAlg
}

return nil
}

// Equal returns true if this key config is equal to the other.
func (k *KeyConfig) Equal(other *KeyConfig) bool {
return reflect.DeepEqual(k, other)
}

// SigningConfig represents the key configuration used to generate a signed bundle
type SigningConfig struct {
Key string
Expand Down
181 changes: 0 additions & 181 deletions bundle/keys_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ package bundle
import (
"crypto/rsa"
"fmt"
"os"
"path/filepath"
"reflect"
"testing"
Expand Down Expand Up @@ -112,80 +111,6 @@ func TestGetPublicKey(t *testing.T) {
}
}

func TestParseKeysConfig(t *testing.T) {

key := `-----BEGIN PUBLIC KEY----- MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA7nJwME0QNM6g0Ou9Sylj lcIY4cnBcs8oWVHe74bJ7JTgYmDOk2CA14RE3wJNkUKERP/cRdesKDA/BToJXJUr oYvhjXxUYn+i3wK5vOGRY9WUtTF9paIIpIV4USUOwDh3ufhA9K3tyh+ZVsqn80em 0Lj2ME0EgScuk6u0/UYjjNvcmnQl+uDmghG8xBZh7TZW2+aceMwlb4LJIP36VRhg jKQGIxg2rW8ROXgJaFbNRCbiOUUqlq9SUZuhHo8TNOARXXxp9R4Fq7Cl7ZbwWtNP wAtM1y+Z+iyu/i91m0YLlU2XBOGLu9IA8IZjPlbCnk/SygpV9NNwTY9DSQ0QfXcP TGlsbFwzRzTlhH25wEl3j+2Ub9w/NX7Yo+j/Ei9eGZ8cq0bcvEwDeIo98HeNZWrL UUArayRYvh8zutOlzqehw8waFk9AxpfEp9oWekSz8gZw9OL773EhnglYxxjkPHNz k66CufLuTEf6uE9NLE5HnlQMbiqBFirIyAWGKyU3v2tphKvcogxmzzWA51p0GY0l GZvlLNt2NrJv2oGecyl3BLqHnBi+rGAosa/8XgfQT8RIk7YR/tDPDmPfaqSIc0po +NcHYEH82Yv+gfKSK++1fyssGCsSRJs8PFMuPGgv62fFrE/EHSsHJaNWojSYce/T rxm2RaHhw/8O4oKcfrbaRf8CAwEAAQ== -----END PUBLIC KEY-----`

config := fmt.Sprintf(`{"foo": {"algorithm": "HS256", "key": "FdFYFzERwC2uCBB46pZQi4GG85LujR8obt-KWRBICVQ"},
"bar": {"key": %v}
}`, key)

tests := map[string]struct {
input string
result map[string]*KeyConfig
wantErr bool
err error
}{
"valid_config_one_key": {
`{"foo": {"algorithm": "HS256", "key": "FdFYFzERwC2uCBB46pZQi4GG85LujR8obt-KWRBICVQ"}}`,
map[string]*KeyConfig{"foo": {Key: "FdFYFzERwC2uCBB46pZQi4GG85LujR8obt-KWRBICVQ", Algorithm: "HS256"}},
false, nil,
},
"valid_config_two_key": {
config,
map[string]*KeyConfig{
"foo": {Key: "FdFYFzERwC2uCBB46pZQi4GG85LujR8obt-KWRBICVQ", Algorithm: "HS256"},
"bar": {Key: key, Algorithm: "RS256"},
},
false, nil,
},
"invalid_config_no_key": {
`{"foo": {"algorithm": "HS256"}}`,
nil,
true, fmt.Errorf("invalid keys configuration: verification key empty for key ID foo"),
},
"valid_config_default_alg": {
`{"foo": {"key": "FdFYFzERwC2uCBB46pZQi4GG85LujR8obt-KWRBICVQ"}}`,
map[string]*KeyConfig{"foo": {Key: "FdFYFzERwC2uCBB46pZQi4GG85LujR8obt-KWRBICVQ", Algorithm: "RS256"}},
false, nil,
},
"invalid_raw_key_config": {
`{"bar": [1,2,3]}`,
nil,
true, fmt.Errorf("json: cannot unmarshal array into Go value of type bundle.KeyConfig"),
},
"invalid_raw_config": {
`[1,2,3]`,
nil,
true, fmt.Errorf("json: cannot unmarshal array into Go value of type map[string]json.RawMessage"),
},
}

for name, tc := range tests {
t.Run(name, func(t *testing.T) {

kc, err := ParseKeysConfig([]byte(tc.input))
if tc.wantErr {
if err == nil {
t.Fatal("Expected error but got nil")
}

if tc.err != nil && tc.err.Error() != err.Error() {
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
}
} else {
if err != nil {
t.Fatalf("Unexpected error %v", err)
}
}

if !reflect.DeepEqual(kc, tc.result) {
t.Fatalf("Expected key config %v but got %v", tc.result, kc)
}
})
}
}

func TestGetPrivateKey(t *testing.T) {
privateKey := `-----BEGIN RSA PRIVATE KEY-----
MIIJKgIBAAKCAgEA7nJwME0QNM6g0Ou9SyljlcIY4cnBcs8oWVHe74bJ7JTgYmDO
Expand Down Expand Up @@ -287,67 +212,6 @@ EXrJfkELSzO66/ZSjyyWEczXHLyr+Q719BsaGsxie117zSNF6B6UXiitjCr/qQ==
})
}

func TestNewKeyConfig(t *testing.T) {
publicKey := `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA9KaakMv1XKKDaSch3PFR
3a27oaHp1GNTTNqvb1ZaHZXp+wuhYDwc/MTE67x9GCifvQBWzEGorgTq7aisiOyl
vKifwz6/wQ+62WHKG/sqKn2Xikp3P63aBIPlZcHbkyyRmL62yeyuzYoGvLEYel+m
z5SiKGBwviSY0Th2L4e5sGJuk2HOut6emxDi+E2Fuuj5zokFJvIT6Urlq8f3h6+l
GeR6HUOXqoYVf7ff126GP7dticTVBgibxkkuJFmpvQSW6xmxruT4k6iwjzbZHY7P
ypZ/TdlnuGC1cOpAVyU7k32IJ9CRbt3nwEf5U54LRXLLQjFixWZHwKdDiMTF4ws0
+wIDAQAB
-----END PUBLIC KEY-----`

files := map[string]string{
"public.pem": publicKey,
}

test.WithTempFS(files, func(rootDir string) {

kc, err := NewKeyConfig(filepath.Join(rootDir, "public.pem"), "RS256", "read")
if err != nil {
t.Fatalf("Unexpected error %v", err)
}

expected := &KeyConfig{
Key: publicKey,
Algorithm: "RS256",
Scope: "read",
}

if !reflect.DeepEqual(kc, expected) {
t.Fatalf("Expected key config %v but got %v", expected, kc)
}

// secret provided on command-line
kc, err = NewKeyConfig(publicKey, "HS256", "")
if err != nil {
t.Fatalf("Unexpected error %v", err)
}

expected = &KeyConfig{
Key: publicKey,
Algorithm: "HS256",
Scope: "",
}

if !reflect.DeepEqual(kc, expected) {
t.Fatalf("Expected key config %v but got %v", expected, kc)
}

// simulate error while reading file
err = os.Chmod(filepath.Join(rootDir, "public.pem"), 0111)
if err != nil {
t.Fatalf("Unexpected error %v", err)
}

_, err = NewKeyConfig(filepath.Join(rootDir, "public.pem"), "RS256", "read")
if err == nil {
t.Fatal("Expected error but got nil")
}
})
}

func TestGetClaimsErrors(t *testing.T) {
files := map[string]string{
"claims.json": `["foo", "read"]`,
Expand All @@ -374,48 +238,3 @@ func TestGetClaimsErrors(t *testing.T) {
}
})
}

func TestKeyConfigEqual(t *testing.T) {
tests := map[string]struct {
a *KeyConfig
b *KeyConfig
exp bool
}{
"equal": {
&KeyConfig{
Key: "foo",
Algorithm: "RS256",
Scope: "read",
},
&KeyConfig{
Key: "foo",
Algorithm: "RS256",
Scope: "read",
},
true,
},
"not_equal": {
&KeyConfig{
Key: "foo",
Algorithm: "RS256",
Scope: "read",
},
&KeyConfig{
Key: "foo",
Algorithm: "RS256",
Scope: "write",
},
false,
},
}

for name, tc := range tests {
t.Run(name, func(t *testing.T) {
actual := tc.a.Equal(tc.b)

if actual != tc.exp {
t.Fatalf("Expected config equal result %v but got %v", tc.exp, actual)
}
})
}
}
5 changes: 3 additions & 2 deletions cmd/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/bundle"
"github.com/open-policy-agent/opa/compile"
"github.com/open-policy-agent/opa/keys"
"github.com/open-policy-agent/opa/util"
)

Expand Down Expand Up @@ -317,11 +318,11 @@ func buildVerificationConfig(pubKey, pubKeyID, alg, scope string, excludeFiles [
return nil, nil
}

keyConfig, err := bundle.NewKeyConfig(pubKey, alg, scope)
keyConfig, err := keys.NewKeyConfig(pubKey, alg, scope)
if err != nil {
return nil, err
}
return bundle.NewVerificationConfig(map[string]*bundle.KeyConfig{pubKeyID: keyConfig}, pubKeyID, scope, excludeFiles), nil
return bundle.NewVerificationConfig(map[string]*keys.Config{pubKeyID: keyConfig}, pubKeyID, scope, excludeFiles), nil
}

func buildSigningConfig(key, alg, claimsFile string) *bundle.SigningConfig {
Expand Down
6 changes: 4 additions & 2 deletions cmd/sign_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"encoding/json"
"fmt"

"github.com/open-policy-agent/opa/keys"

"github.com/open-policy-agent/opa/internal/file/archive"

"github.com/open-policy-agent/opa/bundle"
Expand Down Expand Up @@ -117,12 +119,12 @@ func TestBundleSignVerification(t *testing.T) {
buf := archive.MustWriteTarGz(filesInBundle)

// bundle verification config
kc := bundle.KeyConfig{
kc := keys.Config{
Key: "mysecret",
Algorithm: "HS256",
}

bvc := bundle.NewVerificationConfig(map[string]*bundle.KeyConfig{"foo": &kc}, "foo", "", nil)
bvc := bundle.NewVerificationConfig(map[string]*keys.Config{"foo": &kc}, "foo", "", nil)
reader := bundle.NewReader(buf).WithBundleVerificationConfig(bvc).WithBaseDir(rootDir)

_, err = reader.Read()
Expand Down
Loading

0 comments on commit 36ba445

Please sign in to comment.