Skip to content
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

sdk: add consent helper - closes #397 #398

Merged
merged 4 commits into from
Mar 24, 2017
Merged
Show file tree
Hide file tree
Changes from 3 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: 1 addition & 1 deletion cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func TestExecute(t *testing.T) {
c.args = append(c.args, []string{"--skip-tls-verify", "--config", path}...)
RootCmd.SetArgs(c.args)

t.Run(fmt.Sprintf("command=%v", c.args), func (t *testing.T) {
t.Run(fmt.Sprintf("command=%v", c.args), func(t *testing.T) {
if c.wait != nil {
go func() {
assert.Nil(t, RootCmd.Execute())
Expand Down
38 changes: 19 additions & 19 deletions compose/firewall.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import (
. "github.com/ory-am/hydra/oauth2"
"github.com/ory-am/hydra/pkg"
"github.com/ory-am/hydra/warden"
"github.com/ory-am/hydra/warden/group"
"github.com/ory-am/ladon"
"golang.org/x/oauth2"
"github.com/ory-am/hydra/warden/group"
)

func NewFirewall(issuer string, subject string, scopes fosite.Arguments, p ...ladon.Policy) (firewall.Firewall, *http.Client) {
Expand All @@ -33,24 +33,24 @@ func NewFirewall(issuer string, subject string, scopes fosite.Arguments, p ...la
conf := &oauth2.Config{Scopes: scopes, Endpoint: oauth2.Endpoint{}}

return &warden.LocalWarden{
Warden: ladonWarden,
OAuth2: &fosite.Fosite{
Store: fositeStore,
TokenIntrospectionHandlers: fosite.TokenIntrospectionHandlers{
&foauth2.CoreValidator{
CoreStrategy: pkg.HMACStrategy,
CoreStorage: fositeStore,
ScopeStrategy: fosite.HierarchicScopeStrategy,
Warden: ladonWarden,
OAuth2: &fosite.Fosite{
Store: fositeStore,
TokenIntrospectionHandlers: fosite.TokenIntrospectionHandlers{
&foauth2.CoreValidator{
CoreStrategy: pkg.HMACStrategy,
CoreStorage: fositeStore,
ScopeStrategy: fosite.HierarchicScopeStrategy,
},
},
ScopeStrategy: fosite.HierarchicScopeStrategy,
},
ScopeStrategy: fosite.HierarchicScopeStrategy,
},
Issuer: issuer,
AccessTokenLifespan: time.Hour,
Groups: group.NewMemoryManager(),
}, conf.Client(oauth2.NoContext, &oauth2.Token{
AccessToken: tokens[0][1],
Expiry: time.Now().Add(time.Hour),
TokenType: "bearer",
})
Issuer: issuer,
AccessTokenLifespan: time.Hour,
Groups: group.NewMemoryManager(),
}, conf.Client(oauth2.NoContext, &oauth2.Token{
AccessToken: tokens[0][1],
Expiry: time.Now().Add(time.Hour),
TokenType: "bearer",
})
}
2 changes: 1 addition & 1 deletion config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ type Config struct {
AuthCodeLifespan string `mapstructure:"AUTH_CODE_LIFESPAN" yaml:"-"`
IDTokenLifespan string `mapstructure:"ID_TOKEN_LIFESPAN" yaml:"-"`
ChallengeTokenLifespan string `mapstructure:"CHALLENGE_TOKEN_LIFESPAN" yaml:"-"`
CookieSecret string `mapstructure:"COOKIE_SECRET" yaml:"-"`
CookieSecret string `mapstructure:"COOKIE_SECRET" yaml:"-"`
ForceHTTP bool `yaml:"-"`

cluster *url.URL `yaml:"-"`
Expand Down
2 changes: 0 additions & 2 deletions herodot/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@ func ToError(err error) *Error {
}
}



return &Error{
OriginalError: err,
Name: "internal-error",
Expand Down
16 changes: 8 additions & 8 deletions integration/sql_schema_test.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
package integration

import (
"testing"
"github.com/ory-am/hydra/client"
"github.com/ory-am/fosite"
"github.com/stretchr/testify/require"
"github.com/ory-am/hydra/policy"
"github.com/ory-am/hydra/client"
"github.com/ory-am/hydra/jwk"
"github.com/ory-am/hydra/oauth2"
"github.com/ory-am/ladon"
"github.com/ory-am/hydra/policy"
"github.com/ory-am/hydra/warden/group"
"github.com/ory-am/ladon"
"github.com/stretchr/testify/require"
"testing"
)

func TestSQLSchema(t *testing.T) {
Expand All @@ -20,10 +20,10 @@ func TestSQLSchema(t *testing.T) {
r.ID = "foo"
db := ConnectToMySQL()

cm := &client.SQLManager{DB: db, Hasher: &fosite.BCrypt{}}
cm := &client.SQLManager{DB: db, Hasher: &fosite.BCrypt{}}
gm := group.SQLManager{DB: db}
jm := jwk.SQLManager{DB: db, Cipher: &jwk.AEAD{Key: []byte("11111111111111111111111111111111")}}
om := oauth2.FositeSQLStore{Manager: cm, DB: db }
om := oauth2.FositeSQLStore{Manager: cm, DB: db}
pm, err := policy.NewSQLManager(db)
require.Nil(t, err)

Expand All @@ -37,7 +37,7 @@ func TestSQLSchema(t *testing.T) {
require.Nil(t, cm.CreateClient(&client.Client{ID: "foo"}))
require.Nil(t, om.CreateAccessTokenSession(nil, "asdfasdf", r))
require.Nil(t, gm.CreateGroup(&group.Group{
ID: "asdfas",
ID: "asdfas",
Members: []string{"asdf"},
}))
}
14 changes: 7 additions & 7 deletions policy/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ import (
)

const (
endpoint = "/policies"
scope = "hydra.policies"
policyResource = "rn:hydra:policies"
endpoint = "/policies"
scope = "hydra.policies"
policyResource = "rn:hydra:policies"
policiesResource = "rn:hydra:policies:%s"
)

Expand All @@ -29,9 +29,9 @@ type Handler struct {
func (h *Handler) SetRoutes(r *httprouter.Router) {
r.POST(endpoint, h.Create)
r.GET(endpoint, h.Find)
r.GET(endpoint + "/:id", h.Get)
r.PUT(endpoint + "/:id", h.Update)
r.DELETE(endpoint + "/:id", h.Delete)
r.GET(endpoint+"/:id", h.Get)
r.PUT(endpoint+"/:id", h.Update)
r.DELETE(endpoint+"/:id", h.Delete)
}

func (h *Handler) Find(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
Expand Down Expand Up @@ -84,7 +84,7 @@ func (h *Handler) Create(w http.ResponseWriter, r *http.Request, _ httprouter.Pa
h.H.WriteError(ctx, w, r, errors.WithStack(err))
return
}
h.H.WriteCreated(ctx, w, r, "/policies/" + p.ID, &p)
h.H.WriteCreated(ctx, w, r, "/policies/"+p.ID, &p)
}

func (h *Handler) Get(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
Expand Down
4 changes: 2 additions & 2 deletions policy/manager.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package policy

import (
"github.com/ory-am/ladon"
"github.com/jmoiron/sqlx"
"github.com/ory-am/ladon"
"github.com/rubenv/sql-migrate"
)

Expand All @@ -21,4 +21,4 @@ func NewSQLManager(db *sqlx.DB) (ladon.Manager, error) {
return nil, err
}
return m, nil
}
}
7 changes: 7 additions & 0 deletions sdk/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ type Client struct {
// Groups offers warden group management capabilities.
Groups *group.HTTPManager

// Consent helps you verify consent challenges and sign consent responses.
Consent *Consent

http *http.Client
clusterURL *url.URL
clientID string
Expand Down Expand Up @@ -147,6 +150,10 @@ func Connect(opts ...option) (*Client, error) {
Client: c.http,
}

c.Consent = &Consent{
KeyManager: c.JSONWebKeys,
}

return c, nil
}

Expand Down
134 changes: 134 additions & 0 deletions sdk/consent.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package sdk

import (
"crypto/rsa"
"fmt"
"github.com/dgrijalva/jwt-go"
ejwt "github.com/ory-am/fosite/token/jwt"
"github.com/ory-am/hydra/jwk"
"github.com/ory-am/hydra/oauth2"
"github.com/pkg/errors"
"time"
)

// Consent is a helper for singing and verifying consent challenges. For an exemplary reference implementation, check
// https://github.com/ory/hydra-consent-app-go
type Consent struct {
KeyManager jwk.Manager
}

// ResponseRequest is being used by the consent response singing helper.
type ResponseRequest struct {
// Challenge is the original consent challenge.
Challenge string

// Subject will be the sub claim of the access token. Usually this is a resource owner (user).
Subject string

// Scopes are the scopes the resource owner granted to the application requesting the access token.
Scopes []string

// AccessTokenExtra is arbitrary data that will be available when performing token introspection or warden requests.
AccessTokenExtra interface{}

// IDTokenExtra is arbitrary data that will included as a claim in the ID Token, if requested.
IDTokenExtra interface{}
}

// ChallengeClaims are the decoded claims of a consent challenge.
type ChallengeClaims struct {
// RequestedScopes are the scopes the application requested. Each scope should be explicitly granted by
// the user.
RequestedScopes []string `json:"scp"`

// The ID of the application that initiated the OAuth2 flow.
Audience string `json:"aud"`

// RedirectURL is the url where the consent app will send the user after the consent flow has been completed.
RedirectURL string `json:"redir"`

// ExpiresAt is a unix timestamp of the expiry time.
ExpiresAt float64 `json:"exp"`

// ID is the tokens' ID which will be automatically echoed in the consent response.
ID string `json:"jti"`
}

// Valid tests if the challenge's claims are valid.
func (c *ChallengeClaims) Valid() error {
if time.Now().After(ejwt.ToTime(c.ExpiresAt)) {
return errors.Errorf("Consent challenge expired")
}
return nil
}

// VerifyChallenge verifies a consent challenge and either returns the challenge's claims if it is valid, or an
// error if it is not.
func (c *Consent) VerifyChallenge(challenge string) (*ChallengeClaims, error) {
var claims ChallengeClaims
t, err := jwt.ParseWithClaims(challenge, &claims, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodRSA); !ok {
return nil, errors.Errorf("Unexpected signing method: %v", t.Header["alg"])
}

pk, err := c.KeyManager.GetKey(oauth2.ConsentChallengeKey, "public")
if err != nil {
return nil, err
}

rsaKey, ok := jwk.First(pk.Keys).Key.(*rsa.PublicKey)
if !ok {
return nil, errors.New("Could not convert to RSA Private Key")
}
return rsaKey, nil
})
if err != nil {
return nil, errors.Wrap(err, "The consent chalnge is not a valid JSON Web Token")
}

if !t.Valid {
return nil, errors.Errorf("Consent challenge is invalid")
} else if err := claims.Valid(); err != nil {
return nil, errors.Wrap(err, "The consent challenge claims could not be verified")
}

return &claims, err
}

// GenerateResponse generates a consent response and returns the consent response token, or an error if it is invalid.
func (c *Consent) GenerateResponse(r *ResponseRequest) (string, error) {
Copy link
Member Author

@aeneasr aeneasr Mar 23, 2017

Choose a reason for hiding this comment

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

Instead of returning the consent response token here, we could probably return the URL instead. The former requires us to do something like this:

response, err := c.GenerateResponse(/* ... */)
http.Redirect(r,w,claims.RedirectURL + "&consent=" + response)

while the latter would allow for an easier flow:

redirectURL, err := c.GenerateResponse(/* ... */)
http.Redirect(r,w redirectURL)

To deny consent, the idea is to have:

redirectURL, err := c.DenyConsent(/* ... */)
http.Redirect(r,w redirectURL)

Currently this would be possible with:

http.Redirect(r,w,claims.RedirectURL + "&consent=deny")

challenge, err := c.VerifyChallenge(r.Challenge)
if err != nil {
return "", err
}

token := jwt.New(jwt.SigningMethodRS256)
token.Claims = jwt.MapClaims{
"jti": challenge.ID,
"scp": r.Scopes,
"aud": challenge.Audience,
"exp": challenge.ExpiresAt,
"sub": r.Subject,
"at_ext": r.AccessTokenExtra,
"id_ext": r.IDTokenExtra,
}

ks, err := c.KeyManager.GetKey(oauth2.ConsentEndpointKey, "private")
if err != nil {
return "", errors.WithStack(err)
}

rsaKey, ok := jwk.First(ks.Keys).Key.(*rsa.PrivateKey)
if !ok {
return "", errors.New("Could not convert to RSA Private Key")
}

var signature, encoded string
if encoded, err = token.SigningString(); err != nil {
return "", errors.WithStack(err)
} else if signature, err = token.Method.Sign(encoded, rsaKey); err != nil {
return "", errors.WithStack(err)
}

return fmt.Sprintf("%s.%s", encoded, signature), nil
}
64 changes: 64 additions & 0 deletions sdk/consent_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package sdk

import (
"encoding/base64"
"encoding/json"
"github.com/gorilla/sessions"
"github.com/ory-am/fosite"
"github.com/ory-am/hydra/jwk"
"github.com/ory-am/hydra/oauth2"
"github.com/square/go-jose"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"strings"
"testing"
"time"
)

func genKey() *jose.JsonWebKeySet {
g := &jwk.RS256Generator{}
k, _ := g.Generate("")
return k
}

func TestConsentHelper(t *testing.T) {
km := &jwk.MemoryManager{Keys: map[string]*jose.JsonWebKeySet{}}
km.AddKeySet(oauth2.ConsentChallengeKey, genKey())
km.AddKeySet(oauth2.ConsentEndpointKey, genKey())

_, err := km.GetKey(oauth2.ConsentChallengeKey, "private")
require.Nil(t, err)
c := Consent{KeyManager: km}
s := oauth2.DefaultConsentStrategy{
KeyManager: km,
DefaultChallengeLifespan: time.Hour,
}

ar := fosite.NewAuthorizeRequest()
ar.Client = &fosite.DefaultClient{ID: "foobarclient"}
challenge, err := s.IssueChallenge(ar, "/lightyear", &sessions.Session{Values: map[interface{}]interface{}{}})
require.Nil(t, err)

claims, err := c.VerifyChallenge(challenge)
require.Nil(t, err)
assert.Equal(t, claims.Audience, "foobarclient")
assert.Equal(t, claims.RedirectURL, "/lightyear")
assert.NotEmpty(t, claims.ID)

resp, err := c.GenerateResponse(&ResponseRequest{
Challenge: challenge,
Subject: "buzz",
Scopes: []string{"offline", "openid"},
})
require.Nil(t, err)

var dec map[string]interface{}
result, err := base64.RawURLEncoding.DecodeString(strings.Split(resp, ".")[1])
require.Nil(t, err)

require.Nil(t, json.Unmarshal(result, &dec))
assert.Equal(t, dec["jti"], claims.ID)
t.Logf("%v", dec["jti"])
assert.Equal(t, dec["scp"].([]interface{}), []interface{}{"offline", "openid"})
assert.Equal(t, dec["sub"], "buzz")
}
Loading