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

oauth2: Introduce audience capabilities #327

Merged
merged 5 commits into from
Oct 31, 2018
Merged
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
3 changes: 3 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ install:
- go get github.com/mattn/goveralls golang.org/x/tools/cmd/cover github.com/pierrre/gotestcover github.com/bradfitz/goimports

script:
- curl -L https://git.io/vp6lP | sh
- mv ./bin/* $GOPATH/bin
- gometalinter --disable-all --enable=gofmt --enable=vet --vendor ./...
- touch ./coverage.tmp
- |
echo 'mode: atomic' > coverage.txt
Expand Down
45 changes: 45 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,51 @@ bumps (`0.1.0` -> `0.2.0`).

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

## 0.27.0

This PR adds the ability to specify a target audience for OAuth 2.0 Access Tokens.

### Conceptual Changes

From now on, `scope` and `audience` will be checked against the client's whitelisted scope and audience on every
refresh token exchange. This prevents clients, which no longer are allowed to request a certain audience or scope,
to keep using those values with existing refresh tokens.

### API Changes

```
type fosite.Client interface {
+ // GetAudience returns the allowed audience(s) for this client.
+ GetAudience() Arguments
}
```

```
type fosite.Request struct {
- Scopes Argument
+ RequestedScope Argument

- GrantedScopes Argument
+ GrantedScope Argument
}
```

```
type fosite.Requester interface {
+ // GetRequestedAudience returns the requested audiences for this request.
+ GetRequestedAudience() (audience Arguments)

+ // SetRequestedAudience sets the requested audienc.
+ SetRequestedAudience(audience Arguments)

+ // GetGrantedAudience returns all granted scopes.
+ GetGrantedAudience() (grantedAudience Arguments)

+ // GrantAudience marks a request's audience as granted.
+ GrantAudience(audience string)
}
```

## 0.26.0

This release makes it easier to define custom JWT Containers for access tokens when using the JWT strategy. To do that,
Expand Down
1 change: 1 addition & 0 deletions access_request_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ func (f *Fosite) NewAccessRequest(ctx context.Context, r *http.Request, session
}

accessRequest.SetRequestedScopes(removeEmpty(strings.Split(r.PostForm.Get("scope"), " ")))
accessRequest.SetRequestedAudience(removeEmpty(strings.Split(r.PostForm.Get("audience"), " ")))
accessRequest.GrantTypes = removeEmpty(strings.Split(r.PostForm.Get("grant_type"), " "))
if len(accessRequest.GrantTypes) < 1 {
return accessRequest, errors.WithStack(ErrInvalidRequest.WithHint(`Request parameter "grant_type"" is missing`))
Expand Down
2 changes: 1 addition & 1 deletion access_request_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func TestNewAccessRequest(t *testing.T) {
defer ctrl.Finish()

client := &DefaultClient{}
fosite := &Fosite{Store: store, Hasher: hasher}
fosite := &Fosite{Store: store, Hasher: hasher, AudienceMatchingStrategy: DefaultAudienceMatchingStrategy}
for k, c := range []struct {
header http.Header
form url.Values
Expand Down
4 changes: 4 additions & 0 deletions access_request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,12 @@ func TestAccessRequest(t *testing.T) {
ar.GrantTypes = Arguments{"foobar"}
ar.Client = &DefaultClient{}
ar.GrantScope("foo")
ar.SetRequestedAudience(Arguments{"foo", "foo", "bar"})
ar.SetRequestedScopes(Arguments{"foo", "foo", "bar"})
assert.True(t, ar.GetGrantedScopes().Has("foo"))
assert.NotNil(t, ar.GetRequestedAt())
assert.Equal(t, ar.GrantTypes, ar.GetGrantTypes())
assert.Equal(t, Arguments{"foo", "bar"}, ar.RequestedAudience)
assert.Equal(t, Arguments{"foo", "bar"}, ar.RequestedScope)
assert.Equal(t, ar.Client, ar.GetClient())
}
60 changes: 60 additions & 0 deletions audience_strategy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package fosite

import (
"net/http"
"net/url"
"strings"

"github.com/pkg/errors"

"github.com/ory/go-convenience/stringsx"
)

type AudienceMatchingStrategy func(haystack []string, needle []string) error

func DefaultAudienceMatchingStrategy(haystack []string, needle []string) error {
if len(needle) == 0 {
return nil
}

for _, n := range needle {
nu, err := url.Parse(n)
if err != nil {
return errors.WithStack(ErrInvalidRequest.WithHintf(`Unable to parse requested audience "%s".`, n).WithDebug(err.Error()))
}

var found bool
for _, h := range haystack {
hu, err := url.Parse(h)
if err != nil {
return errors.WithStack(ErrInvalidRequest.WithHintf(`Unable to parse whitelisted audience "%s".`, h).WithDebug(err.Error()))
}

allowedPath := strings.TrimRight(hu.Path, "/")
if nu.Scheme == hu.Scheme &&
nu.Host == hu.Host &&
(nu.Path == hu.Path ||
nu.Path == allowedPath ||
len(nu.Path) > len(allowedPath) && strings.TrimRight(nu.Path[:len(allowedPath)+1], "/")+"/" == allowedPath+"/") {
found = true
}
}

if !found {
return errors.WithStack(ErrInvalidRequest.WithHintf(`Requested audience "%s" has not been whitelisted by the OAuth 2.0 Client.`, n))
}
}

return nil
}

func (f *Fosite) validateAuthorizeAudience(r *http.Request, request *AuthorizeRequest) error {
audience := stringsx.Splitx(request.Form.Get("audience"), " ")

if err := f.AudienceMatchingStrategy(request.Client.GetAudience(), audience); err != nil {
return err
}

request.SetRequestedAudience(Arguments(audience))
return nil
}
96 changes: 96 additions & 0 deletions audience_strategy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package fosite

import (
"fmt"
"testing"

"github.com/stretchr/testify/require"
)

func TestDefaultAudienceMatchingStrategy(t *testing.T) {
for k, tc := range []struct {
h []string
n []string
err bool
}{
{
h: []string{},
n: []string{},
err: false,
},
{
h: []string{"http://foo/bar"},
n: []string{},
err: false,
},
{
h: []string{},
n: []string{"http://foo/bar"},
err: true,
},
{
h: []string{"https://cloud.ory.sh/api/users"},
n: []string{"https://cloud.ory.sh/api/users"},
err: false,
},
{
h: []string{"https://cloud.ory.sh/api/users"},
n: []string{"https://cloud.ory.sh/api/users/"},
err: false,
},
{
h: []string{"https://cloud.ory.sh/api/users/"},
n: []string{"https://cloud.ory.sh/api/users/"},
err: false,
},
{
h: []string{"https://cloud.ory.sh/api/users/"},
n: []string{"https://cloud.ory.sh/api/users"},
err: false,
},
{
h: []string{"https://cloud.ory.sh/api/users"},
n: []string{"https://cloud.ory.sh/api/users/1234"},
err: false,
},
{
h: []string{"https://cloud.ory.sh/api/users"},
n: []string{"https://cloud.ory.sh/api/users", "https://cloud.ory.sh/api/users/", "https://cloud.ory.sh/api/users/1234"},
err: false,
},
{
h: []string{"https://cloud.ory.sh/api/users", "https://cloud.ory.sh/api/tenants"},
n: []string{"https://cloud.ory.sh/api/users", "https://cloud.ory.sh/api/users/", "https://cloud.ory.sh/api/users/1234", "https://cloud.ory.sh/api/tenants"},
err: false,
},
{
h: []string{"https://cloud.ory.sh/api/users"},
n: []string{"https://cloud.ory.sh/api/users1234"},
err: true,
},
{
h: []string{"https://cloud.ory.sh/api/users"},
n: []string{"http://cloud.ory.sh/api/users"},
err: true,
},
{
h: []string{"https://cloud.ory.sh/api/users"},
n: []string{"https://cloud.ory.sh:8000/api/users"},
err: true,
},
{
h: []string{"https://cloud.ory.sh/api/users"},
n: []string{"https://cloud.ory.xyz/api/users"},
err: true,
},
} {
t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) {
err := DefaultAudienceMatchingStrategy(tc.h, tc.n)
if tc.err {
require.Error(t, err)
} else {
require.NoError(t, err)
}
})
}
}
9 changes: 7 additions & 2 deletions authorize_request_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,10 @@ import (
"strings"

"github.com/dgrijalva/jwt-go"
"github.com/pkg/errors"

"github.com/ory/go-convenience/stringslice"
"github.com/ory/go-convenience/stringsx"
"github.com/pkg/errors"
)

func (f *Fosite) authorizeRequestParametersFromOpenIDConnectRequest(request *AuthorizeRequest) error {
Expand Down Expand Up @@ -175,7 +176,7 @@ func (f *Fosite) validateAuthorizeRedirectURI(r *http.Request, request *Authoriz
}

func (f *Fosite) validateAuthorizeScope(r *http.Request, request *AuthorizeRequest) error {
scope := removeEmpty(strings.Split(request.Form.Get("scope"), " "))
scope := stringsx.Splitx(request.Form.Get("scope"), " ")
for _, permission := range scope {
if !f.ScopeStrategy(request.Client.GetScopes(), permission) {
return errors.WithStack(ErrInvalidScope.WithHintf(`The OAuth 2.0 Client is not allowed to request scope "%s".`, permission))
Expand Down Expand Up @@ -243,6 +244,10 @@ func (f *Fosite) NewAuthorizeRequest(ctx context.Context, r *http.Request) (Auth
return request, err
}

if err := f.validateAuthorizeAudience(r, request); err != nil {
return request, err
}

if len(request.Form.Get("registration")) > 0 {
return request, errors.WithStack(ErrRegistrationNotSupported)
}
Expand Down
Loading