Skip to content

Add jwks support #101

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,5 @@ WORKDIR /go/src/github.com/coreos/jwtproxy/

RUN go install -v github.com/coreos/jwtproxy/cmd/jwtproxy
RUN rm -r /usr/local/go

EXPOSE 8080
2 changes: 2 additions & 0 deletions cmd/jwtproxy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import (
_ "github.com/coreos/jwtproxy/jwt/keyserver/keyregistry"
_ "github.com/coreos/jwtproxy/jwt/keyserver/keyregistry/keycache/memory"
_ "github.com/coreos/jwtproxy/jwt/keyserver/preshared"
_ "github.com/coreos/jwtproxy/jwt/keyserver/jwks"
_ "github.com/coreos/jwtproxy/jwt/keyserver/jwks/keycache/memory"
_ "github.com/coreos/jwtproxy/jwt/noncestorage/local"
_ "github.com/coreos/jwtproxy/jwt/privatekey/autogenerated"
_ "github.com/coreos/jwtproxy/jwt/privatekey/preshared"
Expand Down
184 changes: 184 additions & 0 deletions jwt/keyserver/jwks/jwks.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
// Copyright 2016 CoreOS, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package jwks

import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path"
"sync"
"time"

"github.com/coreos/go-oidc/jose"
"github.com/coreos/go-oidc/key"
"github.com/gregjones/httpcache"
"gopkg.in/yaml.v2"

"github.com/coreos/jwtproxy/config"
"github.com/coreos/jwtproxy/jwt/keyserver"
"github.com/coreos/jwtproxy/jwt/keyserver/jwks/keycache"
)

func init() {
keyserver.RegisterReader("jwks", constructReader)
}

type client struct {
cache keycache.Cache
jwks *url.URL
signerParams config.SignerParams
stopping chan struct{}
inFlight *sync.WaitGroup
httpClient *http.Client
}

type Config struct {
Jwks config.URL `yaml:"jwks"`
}

type ReaderConfig struct {
Config `yaml:",inline"'`
Cache *config.RegistrableComponentConfig `yaml:"cache"`
}

func (krc *client) GetPublicKey(issuer string, keyID string) (*key.PublicKey, error) {
// Query java web key set for a public key matching the given issuer and key ID.
pubkeyURL := krc.absURL(keyID)
pubkeyReq, err := krc.prepareRequest("GET", pubkeyURL, nil)
if err != nil {
return nil, err
}
resp, err := krc.httpClient.Do(pubkeyReq)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
switch resp.StatusCode {
case http.StatusNotFound:
return nil, keyserver.ErrPublicKeyNotFound
case http.StatusForbidden:
return nil, keyserver.ErrPublicKeyExpired
default:
return nil, keyserver.ErrUnkownResponse
}
}

// Decode the public key we received as a JSON-encoded JWK.
var d struct {
Keys []jose.JWK `json:"keys"`
}
jsonDecoder := json.NewDecoder(resp.Body)
err = jsonDecoder.Decode(&d)
if err != nil {
return nil, err
}
if len(d.Keys) == 0 {
return nil, errors.New("zero keys in response")
}
ks := key.NewPublicKeySet(d.Keys, time.Now())

return ks.Key(keyID), nil
}

func (krc *client) Stop() <-chan struct{} {
finished := make(chan struct{})
// Stop the in flight requests
close(krc.stopping)
go func() {
krc.inFlight.Wait()

// Now stop the cache
if krc.cache != nil {
<-krc.cache.Stop()
}

close(finished)
}()
return finished
}

func (krc *client) prepareRequest(method string, url *url.URL, body io.Reader) (*http.Request, error) {
// Create an HTTP request to the key server to publish a new key.
req, err := http.NewRequest(method, url.String(), body)
if err != nil {
return nil, err
}

if method == "PUT" || method == "POST" {
req.Header.Add("Content-Type", "application/json")
}

// Add our user agent.
req.Header.Set("User-Agent", "JWTProxy/0.1.0")

return req, nil
}

func (krc *client) absURL(pathParams ...string) *url.URL {
escaped := make([]string, 0, len(pathParams)+1)
escaped = append(escaped, krc.jwks.Path)
for _, pathParam := range pathParams {
escaped = append(escaped, url.QueryEscape(pathParam))
}

absPath := path.Join(escaped...)
relurl, err := url.Parse(absPath)
if err != nil {
panic(err)
}
return krc.jwks.ResolveReference(relurl)
}

func constructReader(registrableComponentConfig config.RegistrableComponentConfig) (keyserver.Reader, error) {
bytes, err := yaml.Marshal(registrableComponentConfig.Options)
if err != nil {
return nil, err
}
var cfg ReaderConfig
err = yaml.Unmarshal(bytes, &cfg)
if err != nil {
return nil, err
}

// Construct the public key cache.
cacheConfig := config.RegistrableComponentConfig{
Type: "memory",
}
if cfg.Cache != nil {
cacheConfig = *cfg.Cache
}

cache, err := keycache.NewCache(cacheConfig)
if err != nil {
return nil, fmt.Errorf("Unable to construct cache: %s", err)
}

httpClient := &http.Client{
Transport: httpcache.NewTransport(cache),
}

return &client{
jwks: cfg.Jwks.URL,
inFlight: &sync.WaitGroup{},
stopping: make(chan struct{}),
cache: cache,
httpClient: httpClient,
}, nil
}
51 changes: 51 additions & 0 deletions jwt/keyserver/jwks/keycache/keycache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright 2016 CoreOS, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package keycache

import (
"fmt"

"github.com/gregjones/httpcache"

"github.com/coreos/jwtproxy/config"
"github.com/coreos/jwtproxy/stop"
)

type Constructor func(config.RegistrableComponentConfig) (Cache, error)

type Cache interface {
stop.Stoppable
httpcache.Cache
}

var keycaches = make(map[string]Constructor)

func RegisterCache(name string, c Constructor) {
if c == nil {
panic("server: could not register nil ReaderConstructor")
}
if _, dup := keycaches[name]; dup {
panic("server: could not register duplicate ReaderConstructor: " + name)
}
keycaches[name] = c
}

func NewCache(cfg config.RegistrableComponentConfig) (Cache, error) {
c, ok := keycaches[cfg.Type]
if !ok {
return nil, fmt.Errorf("server: unknown Cache type %q (forgotten import?)", cfg.Type)
}
return c(cfg)
}
44 changes: 44 additions & 0 deletions jwt/keyserver/jwks/keycache/memory/memory.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright 2016 CoreOS, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package memory

import (
log "github.com/Sirupsen/logrus"
"github.com/gregjones/httpcache"

"github.com/coreos/jwtproxy/config"
"github.com/coreos/jwtproxy/jwt/keyserver/jwks/keycache"
"github.com/coreos/jwtproxy/stop"
)

func init() {
keycache.RegisterCache("memory", constructor)
}

type cache struct {
*httpcache.MemoryCache
}

func constructor(registrableComponentConfig config.RegistrableComponentConfig) (keycache.Cache, error) {
log.Debug("Initializing in-memory key cache.")

return &cache{
MemoryCache: httpcache.NewMemoryCache(),
}, nil
}

func (c *cache) Stop() <-chan struct{} {
return stop.AlreadyDone
}