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

fix: requested scope ignored in refresh flow #5

Merged
merged 1 commit into from
Aug 28, 2023
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
19 changes: 19 additions & 0 deletions access_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,22 @@ func NewAccessRequest(session Session) *AccessRequest {
func (a *AccessRequest) GetGrantTypes() Arguments {
return a.GrantTypes
}

func (a *AccessRequest) SetGrantedScopes(scopes Arguments) {
a.GrantedScope = scopes
}

func (a *AccessRequest) SanitizeRestoreRefreshTokenOriginalRequester(requester Requester) Requester {
r := a.Sanitize(nil).(*Request)

ar := &AccessRequest{
Request: *r,
}

ar.SetID(requester.GetID())

ar.SetRequestedScopes(requester.GetRequestedScopes())
ar.SetGrantedScopes(requester.GetGrantedScopes())

return ar
}
63 changes: 54 additions & 9 deletions handler/oauth2/flow_refresh.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ type RefreshTokenGrantHandler struct {
fosite.AudienceStrategyProvider
fosite.RefreshTokenScopesProvider
}

// IgnoreRequestedScopeNotInOriginalGrant determines the action to take when the requested scopes in the refresh
// flow were not originally granted. If false which is the default the handler will automatically return an error.
// If true the handler will filter out / ignore the scopes which were not originally granted.
IgnoreRequestedScopeNotInOriginalGrant bool
}

// HandleTokenEndpointRequest implements https://tools.ietf.org/html/rfc6749#section-6
Expand Down Expand Up @@ -79,13 +84,43 @@ func (c *RefreshTokenGrantHandler) HandleTokenEndpointRequest(ctx context.Contex

request.SetID(originalRequest.GetID())
request.SetSession(originalRequest.GetSession().Clone())
request.SetRequestedScopes(originalRequest.GetRequestedScopes())
/*
There are two key points in the following spec section this addresses:
1. If omitted the scope param should be treated as the same as the scope originally granted by the resource owner.
2. The REQUESTED scope MUST NOT include any scope not originally granted.
scope
OPTIONAL. The scope of the access request as described by Section 3.3. The requested scope MUST NOT
include any scope not originally granted by the resource owner, and if omitted is treated as equal to
the scope originally granted by the resource owner.
See https://www.rfc-editor.org/rfc/rfc6749#section-6
*/

// Addresses point 1 of the text in RFC6749 Section 6.
if len(request.GetRequestedScopes()) == 0 {
request.SetRequestedScopes(originalRequest.GetGrantedScopes())
}

request.SetRequestedAudience(originalRequest.GetRequestedAudience())

for _, scope := range originalRequest.GetGrantedScopes() {
if !c.Config.GetScopeStrategy(ctx)(request.GetClient().GetScopes(), scope) {
strategy := c.Config.GetScopeStrategy(ctx)
originalScopes := originalRequest.GetGrantedScopes()

for _, scope := range request.GetRequestedScopes() {
if !strategy(originalScopes, scope) {
if c.IgnoreRequestedScopeNotInOriginalGrant {
// Skips addressing point 2 of the text in RFC6749 Section 6 and instead just prevents the scope
// requested from being granted.
continue
} else {
// Addresses point 2 of the text in RFC6749 Section 6.
return errorsx.WithStack(fosite.ErrInvalidScope.WithHintf("The requested scope '%s' was not originally granted by the resource owner.", scope))
}
}

if !strategy(request.GetClient().GetScopes(), scope) {
return errorsx.WithStack(fosite.ErrInvalidScope.WithHintf("The OAuth 2.0 Client is not allowed to request scope '%s'.", scope))
}

request.GrantScope(scope)
}

Expand Down Expand Up @@ -134,26 +169,36 @@ func (c *RefreshTokenGrantHandler) PopulateTokenEndpointResponse(ctx context.Con
err = c.handleRefreshTokenEndpointStorageError(ctx, err)
}()

ts, err := c.TokenRevocationStorage.GetRefreshTokenSession(ctx, signature, nil)
originalRequest, err := c.TokenRevocationStorage.GetRefreshTokenSession(ctx, signature, nil)
if err != nil {
return err
} else if err := c.TokenRevocationStorage.RevokeAccessToken(ctx, ts.GetID()); err != nil {
} else if err := c.TokenRevocationStorage.RevokeAccessToken(ctx, originalRequest.GetID()); err != nil {
return err
}

if err := c.TokenRevocationStorage.RevokeRefreshTokenMaybeGracePeriod(ctx, ts.GetID(), signature); err != nil {
if err := c.TokenRevocationStorage.RevokeRefreshTokenMaybeGracePeriod(ctx, originalRequest.GetID(), signature); err != nil {
return err
}

storeReq := requester.Sanitize([]string{})
storeReq.SetID(ts.GetID())
storeReq.SetID(originalRequest.GetID())

if err = c.TokenRevocationStorage.CreateAccessTokenSession(ctx, accessSignature, storeReq); err != nil {
return err
}

if err = c.TokenRevocationStorage.CreateRefreshTokenSession(ctx, refreshSignature, storeReq); err != nil {
return err
if rtRequest, ok := requester.(fosite.RefreshTokenAccessRequester); ok {
rtStoreReq := rtRequest.SanitizeRestoreRefreshTokenOriginalRequester(originalRequest)

rtStoreReq.SetSession(requester.GetSession().Clone())

if err = c.TokenRevocationStorage.CreateRefreshTokenSession(ctx, refreshSignature, rtStoreReq); err != nil {
return err
}
} else {
if err = c.TokenRevocationStorage.CreateRefreshTokenSession(ctx, refreshSignature, storeReq); err != nil {
return err
}
}

responder.SetAccessToken(accessToken)
Expand Down
97 changes: 94 additions & 3 deletions handler/oauth2/flow_refresh_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,12 +173,103 @@ func TestRefreshFlow_HandleTokenEndpointRequest(t *testing.T) {
assert.NotEqual(t, sess, areq.Session)
assert.NotEqual(t, time.Now().UTC().Add(-time.Hour).Round(time.Hour), areq.RequestedAt)
assert.Equal(t, fosite.Arguments{"foo", "offline"}, areq.GrantedScope)
assert.Equal(t, fosite.Arguments{"foo", "bar", "offline"}, areq.RequestedScope)
assert.Equal(t, fosite.Arguments{"foo", "offline"}, areq.RequestedScope)
assert.NotEqual(t, url.Values{"foo": []string{"bar"}}, areq.Form)
assert.Equal(t, time.Now().Add(time.Hour).UTC().Round(time.Second), areq.GetSession().GetExpiresAt(fosite.AccessToken))
assert.Equal(t, time.Now().Add(time.Hour).UTC().Round(time.Second), areq.GetSession().GetExpiresAt(fosite.RefreshToken))
},
},
{
description: "should pass with scope in form",
setup: func(config *fosite.Config) {
areq.GrantTypes = fosite.Arguments{"refresh_token"}
areq.Client = &fosite.DefaultClient{
ID: "foo",
GrantTypes: fosite.Arguments{"refresh_token"},
Scopes: []string{"foo", "bar", "baz", "offline"},
}

token, sig, err := strategy.GenerateRefreshToken(nil, nil)
require.NoError(t, err)

areq.Form.Add("refresh_token", token)
areq.Form.Add("scope", "foo bar baz offline")
err = store.CreateRefreshTokenSession(nil, sig, &fosite.Request{
Client: areq.Client,
GrantedScope: fosite.Arguments{"foo", "bar", "baz", "offline"},
RequestedScope: fosite.Arguments{"foo", "bar", "baz", "offline"},
Session: sess,
Form: url.Values{"foo": []string{"bar"}},
RequestedAt: time.Now().UTC().Add(-time.Hour).Round(time.Hour),
})
require.NoError(t, err)
},
expect: func(t *testing.T) {
assert.Equal(t, fosite.Arguments{"foo", "bar", "baz", "offline"}, areq.GrantedScope)
assert.Equal(t, fosite.Arguments{"foo", "bar", "baz", "offline"}, areq.RequestedScope)
},
},
{
description: "should pass with scope in form and should narrow scopes",
setup: func(config *fosite.Config) {
areq.GrantTypes = fosite.Arguments{"refresh_token"}
areq.Client = &fosite.DefaultClient{
ID: "foo",
GrantTypes: fosite.Arguments{"refresh_token"},
Scopes: []string{"foo", "bar", "baz", "offline"},
}

token, sig, err := strategy.GenerateRefreshToken(nil, nil)
require.NoError(t, err)

areq.Form.Add("refresh_token", token)
areq.Form.Add("scope", "foo bar offline")
areq.SetRequestedScopes(fosite.Arguments{"foo", "bar", "offline"})

err = store.CreateRefreshTokenSession(nil, sig, &fosite.Request{
Client: areq.Client,
GrantedScope: fosite.Arguments{"foo", "bar", "baz", "offline"},
RequestedScope: fosite.Arguments{"foo", "bar", "baz", "offline"},
Session: sess,
Form: url.Values{"foo": []string{"bar"}},
RequestedAt: time.Now().UTC().Add(-time.Hour).Round(time.Hour),
})
require.NoError(t, err)
},
expect: func(t *testing.T) {
assert.Equal(t, fosite.Arguments{"foo", "bar", "offline"}, areq.GrantedScope)
assert.Equal(t, fosite.Arguments{"foo", "bar", "offline"}, areq.RequestedScope)
},
},
{
description: "should fail with broadened scopes even if the client can request it",
setup: func(config *fosite.Config) {
areq.GrantTypes = fosite.Arguments{"refresh_token"}
areq.Client = &fosite.DefaultClient{
ID: "foo",
GrantTypes: fosite.Arguments{"refresh_token"},
Scopes: []string{"foo", "bar", "baz", "offline"},
}

token, sig, err := strategy.GenerateRefreshToken(nil, nil)
require.NoError(t, err)

areq.Form.Add("refresh_token", token)
areq.Form.Add("scope", "foo bar offline")
areq.SetRequestedScopes(fosite.Arguments{"foo", "bar", "offline"})

err = store.CreateRefreshTokenSession(nil, sig, &fosite.Request{
Client: areq.Client,
GrantedScope: fosite.Arguments{"foo", "baz", "offline"},
RequestedScope: fosite.Arguments{"foo", "baz", "offline"},
Session: sess,
Form: url.Values{"foo": []string{"bar"}},
RequestedAt: time.Now().UTC().Add(-time.Hour).Round(time.Hour),
})
require.NoError(t, err)
},
expectErr: fosite.ErrInvalidScope,
},
{
description: "should pass with custom client lifespans",
setup: func(config *fosite.Config) {
Expand Down Expand Up @@ -211,7 +302,7 @@ func TestRefreshFlow_HandleTokenEndpointRequest(t *testing.T) {
assert.NotEqual(t, sess, areq.Session)
assert.NotEqual(t, time.Now().UTC().Add(-time.Hour).Round(time.Hour), areq.RequestedAt)
assert.Equal(t, fosite.Arguments{"foo", "offline"}, areq.GrantedScope)
assert.Equal(t, fosite.Arguments{"foo", "bar", "offline"}, areq.RequestedScope)
assert.Equal(t, fosite.Arguments{"foo", "offline"}, areq.RequestedScope)
assert.NotEqual(t, url.Values{"foo": []string{"bar"}}, areq.Form)
internal.RequireEqualTime(t, time.Now().Add(*internal.TestLifespans.RefreshTokenGrantAccessTokenLifespan).UTC(), areq.GetSession().GetExpiresAt(fosite.AccessToken), time.Minute)
internal.RequireEqualTime(t, time.Now().Add(*internal.TestLifespans.RefreshTokenGrantRefreshTokenLifespan).UTC(), areq.GetSession().GetExpiresAt(fosite.RefreshToken), time.Minute)
Expand Down Expand Up @@ -272,7 +363,7 @@ func TestRefreshFlow_HandleTokenEndpointRequest(t *testing.T) {
assert.NotEqual(t, sess, areq.Session)
assert.NotEqual(t, time.Now().UTC().Add(-time.Hour).Round(time.Hour), areq.RequestedAt)
assert.Equal(t, fosite.Arguments{"foo"}, areq.GrantedScope)
assert.Equal(t, fosite.Arguments{"foo", "bar"}, areq.RequestedScope)
assert.Equal(t, fosite.Arguments{"foo"}, areq.RequestedScope)
assert.NotEqual(t, url.Values{"foo": []string{"bar"}}, areq.Form)
assert.Equal(t, time.Now().Add(time.Hour).UTC().Round(time.Second), areq.GetSession().GetExpiresAt(fosite.AccessToken))
assert.Equal(t, time.Now().Add(time.Hour).UTC().Round(time.Second), areq.GetSession().GetExpiresAt(fosite.RefreshToken))
Expand Down
20 changes: 17 additions & 3 deletions integration/helper_endpoints_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,22 @@ func authEndpointHandler(t *testing.T, oauth2 fosite.OAuth2Provider, session fos
return
}

if ar.GetRequestedScopes().Has("fosite") {
ar.GrantScope("fosite")
if ar.GetClient().GetID() == "grant-all-requested-scopes-client" {
for _, scope := range ar.GetRequestedScopes() {
ar.GrantScope(scope)
}
} else {
if ar.GetRequestedScopes().Has("fosite") {
ar.GrantScope("fosite")
}

if ar.GetRequestedScopes().Has("offline") {
ar.GrantScope("offline")
}

if ar.GetRequestedScopes().Has("openid") {
ar.GrantScope("openid")
}
}

if ar.GetRequestedScopes().Has("offline") {
Expand Down Expand Up @@ -146,7 +160,7 @@ func tokenEndpointHandler(t *testing.T, provider fosite.OAuth2Provider) func(rw

response, err := provider.NewAccessResponse(ctx, accessRequest)
if err != nil {
t.Logf("Access request failed because: %+v", err)
t.Logf("Access request failed because: %+v", fosite.ErrorToRFC6749Error(err).WithExposeDebug(true).GetDescription())
t.Logf("Request: %+v", accessRequest)
provider.WriteAccessError(req.Context(), rw, accessRequest, err)
return
Expand Down
Loading