language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
Go | hydra/oauth2/equalKeys_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2
import "testing"
func TestAssertObjectsAreEqualByKeys(t *testing.T) {
type foo struct {
Name string
Body int
}
a := &foo{"foo", 1}
b := &foo{"bar", 1}
c := &foo{"baz", 3}
AssertObjectKeysEqual(t, a, a, "Name", "Body")
AssertObjectKeysNotEqual(t, a, b, "Name")
AssertObjectKeysNotEqual(t, a, c, "Name", "Body")
} |
Go | hydra/oauth2/fosite_store_helpers.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2
import (
"context"
"crypto/sha256"
"fmt"
"net/url"
"testing"
"time"
"github.com/ory/hydra/v2/flow"
"github.com/ory/hydra/v2/jwk"
"github.com/go-jose/go-jose/v3"
"github.com/gobuffalo/pop/v6"
"github.com/pborman/uuid"
"github.com/ory/fosite/handler/rfc7523"
"github.com/ory/hydra/v2/oauth2/trust"
"github.com/ory/hydra/v2/x"
"github.com/ory/fosite/storage"
"github.com/ory/x/sqlxx"
gofrsuuid "github.com/gofrs/uuid"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/ory/fosite"
"github.com/ory/fosite/handler/openid"
"github.com/ory/x/sqlcon"
"github.com/ory/hydra/v2/client"
)
func signatureFromJTI(jti string) string {
return fmt.Sprintf("%x", sha256.Sum256([]byte(jti)))
}
type BlacklistedJTI struct {
JTI string `db:"-"`
ID string `db:"signature"`
Expiry time.Time `db:"expires_at"`
NID gofrsuuid.UUID `db:"nid"`
}
func (j *BlacklistedJTI) AfterFind(_ *pop.Connection) error {
j.Expiry = j.Expiry.UTC()
return nil
}
func (BlacklistedJTI) TableName() string {
return "hydra_oauth2_jti_blacklist"
}
func NewBlacklistedJTI(jti string, exp time.Time) *BlacklistedJTI {
return &BlacklistedJTI{
JTI: jti,
ID: signatureFromJTI(jti),
// because the database timestamp types are not as accurate as time.Time we truncate to seconds (which should always work)
Expiry: exp.UTC().Truncate(time.Second),
}
}
type AssertionJWTReader interface {
x.FositeStorer
GetClientAssertionJWT(ctx context.Context, jti string) (*BlacklistedJTI, error)
SetClientAssertionJWTRaw(context.Context, *BlacklistedJTI) error
}
var defaultRequest = fosite.Request{
ID: "blank",
RequestedAt: time.Now().UTC().Round(time.Second),
Client: &client.Client{LegacyClientID: "foobar"},
RequestedScope: fosite.Arguments{"fa", "ba"},
GrantedScope: fosite.Arguments{"fa", "ba"},
RequestedAudience: fosite.Arguments{"ad1", "ad2"},
GrantedAudience: fosite.Arguments{"ad1", "ad2"},
Form: url.Values{"foo": []string{"bar", "baz"}},
Session: &Session{DefaultSession: &openid.DefaultSession{Subject: "bar"}},
}
var lifespan = time.Hour
var flushRequests = []*fosite.Request{
{
ID: "flush-1",
RequestedAt: time.Now().Round(time.Second),
Client: &client.Client{LegacyClientID: "foobar"},
RequestedScope: fosite.Arguments{"fa", "ba"},
GrantedScope: fosite.Arguments{"fa", "ba"},
Form: url.Values{"foo": []string{"bar", "baz"}},
Session: &Session{DefaultSession: &openid.DefaultSession{Subject: "bar"}},
},
{
ID: "flush-2",
RequestedAt: time.Now().Round(time.Second).Add(-(lifespan + time.Minute)),
Client: &client.Client{LegacyClientID: "foobar"},
RequestedScope: fosite.Arguments{"fa", "ba"},
GrantedScope: fosite.Arguments{"fa", "ba"},
Form: url.Values{"foo": []string{"bar", "baz"}},
Session: &Session{DefaultSession: &openid.DefaultSession{Subject: "bar"}},
},
{
ID: "flush-3",
RequestedAt: time.Now().Round(time.Second).Add(-(lifespan + time.Hour)),
Client: &client.Client{LegacyClientID: "foobar"},
RequestedScope: fosite.Arguments{"fa", "ba"},
GrantedScope: fosite.Arguments{"fa", "ba"},
Form: url.Values{"foo": []string{"bar", "baz"}},
Session: &Session{DefaultSession: &openid.DefaultSession{Subject: "bar"}},
},
}
func mockRequestForeignKey(t *testing.T, id string, x InternalRegistry, createClient bool) {
cl := &client.Client{LegacyClientID: "foobar"}
cr := &flow.OAuth2ConsentRequest{
Client: cl,
OpenIDConnectContext: new(flow.OAuth2ConsentRequestOpenIDConnectContext),
LoginChallenge: sqlxx.NullString(id),
ID: id,
Verifier: id,
CSRF: id,
AuthenticatedAt: sqlxx.NullTime(time.Now()),
RequestedAt: time.Now(),
}
ctx := context.Background()
if createClient {
require.NoError(t, x.ClientManager().CreateClient(ctx, cl))
}
f, err := x.ConsentManager().CreateLoginRequest(
ctx, &flow.LoginRequest{
Client: cl,
OpenIDConnectContext: new(flow.OAuth2ConsentRequestOpenIDConnectContext),
ID: id,
Verifier: id,
AuthenticatedAt: sqlxx.NullTime(time.Now()),
RequestedAt: time.Now(),
})
require.NoError(t, err)
err = x.ConsentManager().CreateConsentRequest(ctx, f, cr)
require.NoError(t, err)
encodedFlow, err := f.ToConsentVerifier(ctx, x)
require.NoError(t, err)
_, err = x.ConsentManager().HandleConsentRequest(ctx, f, &flow.AcceptOAuth2ConsentRequest{
ConsentRequest: cr,
Session: new(flow.AcceptOAuth2ConsentRequestSession),
AuthenticatedAt: sqlxx.NullTime(time.Now()),
ID: encodedFlow,
RequestedAt: time.Now(),
HandledAt: sqlxx.NullTime(time.Now()),
})
require.NoError(t, err)
}
// TestHelperRunner is used to run the database suite of tests in this package.
// KEEP EXPORTED AND AVAILABLE FOR THIRD PARTIES TO TEST PLUGINS!
func TestHelperRunner(t *testing.T, store InternalRegistry, k string) {
t.Helper()
if k != "memory" {
t.Run(fmt.Sprintf("case=testHelperUniqueConstraints/db=%s", k), testHelperRequestIDMultiples(store, k))
t.Run("case=testFositeSqlStoreTransactionsCommitAccessToken", testFositeSqlStoreTransactionCommitAccessToken(store))
t.Run("case=testFositeSqlStoreTransactionsRollbackAccessToken", testFositeSqlStoreTransactionRollbackAccessToken(store))
t.Run("case=testFositeSqlStoreTransactionCommitRefreshToken", testFositeSqlStoreTransactionCommitRefreshToken(store))
t.Run("case=testFositeSqlStoreTransactionRollbackRefreshToken", testFositeSqlStoreTransactionRollbackRefreshToken(store))
t.Run("case=testFositeSqlStoreTransactionCommitAuthorizeCode", testFositeSqlStoreTransactionCommitAuthorizeCode(store))
t.Run("case=testFositeSqlStoreTransactionRollbackAuthorizeCode", testFositeSqlStoreTransactionRollbackAuthorizeCode(store))
t.Run("case=testFositeSqlStoreTransactionCommitPKCERequest", testFositeSqlStoreTransactionCommitPKCERequest(store))
t.Run("case=testFositeSqlStoreTransactionRollbackPKCERequest", testFositeSqlStoreTransactionRollbackPKCERequest(store))
t.Run("case=testFositeSqlStoreTransactionCommitOpenIdConnectSession", testFositeSqlStoreTransactionCommitOpenIdConnectSession(store))
t.Run("case=testFositeSqlStoreTransactionRollbackOpenIdConnectSession", testFositeSqlStoreTransactionRollbackOpenIdConnectSession(store))
}
t.Run(fmt.Sprintf("case=testHelperCreateGetDeleteAuthorizeCodes/db=%s", k), testHelperCreateGetDeleteAuthorizeCodes(store))
t.Run(fmt.Sprintf("case=testHelperCreateGetDeleteAccessTokenSession/db=%s", k), testHelperCreateGetDeleteAccessTokenSession(store))
t.Run(fmt.Sprintf("case=testHelperNilAccessToken/db=%s", k), testHelperNilAccessToken(store))
t.Run(fmt.Sprintf("case=testHelperCreateGetDeleteOpenIDConnectSession/db=%s", k), testHelperCreateGetDeleteOpenIDConnectSession(store))
t.Run(fmt.Sprintf("case=testHelperCreateGetDeleteRefreshTokenSession/db=%s", k), testHelperCreateGetDeleteRefreshTokenSession(store))
t.Run(fmt.Sprintf("case=testHelperRevokeRefreshToken/db=%s", k), testHelperRevokeRefreshToken(store))
t.Run(fmt.Sprintf("case=testHelperCreateGetDeletePKCERequestSession/db=%s", k), testHelperCreateGetDeletePKCERequestSession(store))
t.Run(fmt.Sprintf("case=testHelperFlushTokens/db=%s", k), testHelperFlushTokens(store, time.Hour))
t.Run(fmt.Sprintf("case=testHelperFlushTokensWithLimitAndBatchSize/db=%s", k), testHelperFlushTokensWithLimitAndBatchSize(store, 3, 2))
t.Run(fmt.Sprintf("case=testFositeStoreSetClientAssertionJWT/db=%s", k), testFositeStoreSetClientAssertionJWT(store))
t.Run(fmt.Sprintf("case=testFositeStoreClientAssertionJWTValid/db=%s", k), testFositeStoreClientAssertionJWTValid(store))
t.Run(fmt.Sprintf("case=testHelperDeleteAccessTokens/db=%s", k), testHelperDeleteAccessTokens(store))
t.Run(fmt.Sprintf("case=testHelperRevokeAccessToken/db=%s", k), testHelperRevokeAccessToken(store))
t.Run(fmt.Sprintf("case=testFositeJWTBearerGrantStorage/db=%s", k), testFositeJWTBearerGrantStorage(store))
}
func testHelperRequestIDMultiples(m InternalRegistry, _ string) func(t *testing.T) {
return func(t *testing.T) {
requestId := uuid.New()
mockRequestForeignKey(t, requestId, m, true)
cl := &client.Client{LegacyClientID: "foobar"}
fositeRequest := &fosite.Request{
ID: requestId,
Client: cl,
RequestedAt: time.Now().UTC().Round(time.Second),
Session: &Session{},
}
for i := 0; i < 4; i++ {
signature := uuid.New()
err := m.OAuth2Storage().CreateRefreshTokenSession(context.TODO(), signature, fositeRequest)
assert.NoError(t, err)
err = m.OAuth2Storage().CreateAccessTokenSession(context.TODO(), signature, fositeRequest)
assert.NoError(t, err)
err = m.OAuth2Storage().CreateOpenIDConnectSession(context.TODO(), signature, fositeRequest)
assert.NoError(t, err)
err = m.OAuth2Storage().CreatePKCERequestSession(context.TODO(), signature, fositeRequest)
assert.NoError(t, err)
err = m.OAuth2Storage().CreateAuthorizeCodeSession(context.TODO(), signature, fositeRequest)
assert.NoError(t, err)
}
}
}
func testHelperCreateGetDeleteOpenIDConnectSession(x InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
m := x.OAuth2Storage()
ctx := context.Background()
_, err := m.GetOpenIDConnectSession(ctx, "4321", &fosite.Request{})
assert.NotNil(t, err)
err = m.CreateOpenIDConnectSession(ctx, "4321", &defaultRequest)
require.NoError(t, err)
res, err := m.GetOpenIDConnectSession(ctx, "4321", &fosite.Request{Session: &Session{}})
require.NoError(t, err)
AssertObjectKeysEqual(t, &defaultRequest, res, "RequestedScope", "GrantedScope", "Form", "Session")
err = m.DeleteOpenIDConnectSession(ctx, "4321")
require.NoError(t, err)
_, err = m.GetOpenIDConnectSession(ctx, "4321", &fosite.Request{})
assert.NotNil(t, err)
}
}
func testHelperCreateGetDeleteRefreshTokenSession(x InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
m := x.OAuth2Storage()
ctx := context.Background()
_, err := m.GetRefreshTokenSession(ctx, "4321", &Session{})
assert.NotNil(t, err)
err = m.CreateRefreshTokenSession(ctx, "4321", &defaultRequest)
require.NoError(t, err)
res, err := m.GetRefreshTokenSession(ctx, "4321", &Session{})
require.NoError(t, err)
AssertObjectKeysEqual(t, &defaultRequest, res, "RequestedScope", "GrantedScope", "Form", "Session")
err = m.DeleteRefreshTokenSession(ctx, "4321")
require.NoError(t, err)
_, err = m.GetRefreshTokenSession(ctx, "4321", &Session{})
assert.NotNil(t, err)
}
}
func testHelperRevokeRefreshToken(x InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
m := x.OAuth2Storage()
ctx := context.Background()
_, err := m.GetRefreshTokenSession(ctx, "1111", &Session{})
assert.Error(t, err)
reqIdOne := uuid.New()
reqIdTwo := uuid.New()
mockRequestForeignKey(t, reqIdOne, x, false)
mockRequestForeignKey(t, reqIdTwo, x, false)
err = m.CreateRefreshTokenSession(ctx, "1111", &fosite.Request{
ID: reqIdOne,
Client: &client.Client{LegacyClientID: "foobar"},
RequestedAt: time.Now().UTC().Round(time.Second),
Session: &Session{}})
require.NoError(t, err)
err = m.CreateRefreshTokenSession(ctx, "1122", &fosite.Request{
ID: reqIdTwo,
Client: &client.Client{LegacyClientID: "foobar"},
RequestedAt: time.Now().UTC().Round(time.Second),
Session: &Session{}})
require.NoError(t, err)
_, err = m.GetRefreshTokenSession(ctx, "1111", &Session{})
require.NoError(t, err)
err = m.RevokeRefreshToken(ctx, reqIdOne)
require.NoError(t, err)
err = m.RevokeRefreshToken(ctx, reqIdTwo)
require.NoError(t, err)
req, err := m.GetRefreshTokenSession(ctx, "1111", &Session{})
assert.NotNil(t, req)
assert.EqualError(t, err, fosite.ErrInactiveToken.Error())
req, err = m.GetRefreshTokenSession(ctx, "1122", &Session{})
assert.NotNil(t, req)
assert.EqualError(t, err, fosite.ErrInactiveToken.Error())
}
}
func testHelperCreateGetDeleteAuthorizeCodes(x InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
m := x.OAuth2Storage()
mockRequestForeignKey(t, "blank", x, false)
ctx := context.Background()
res, err := m.GetAuthorizeCodeSession(ctx, "4321", &Session{})
assert.Error(t, err)
assert.Nil(t, res)
err = m.CreateAuthorizeCodeSession(ctx, "4321", &defaultRequest)
require.NoError(t, err)
res, err = m.GetAuthorizeCodeSession(ctx, "4321", &Session{})
require.NoError(t, err)
AssertObjectKeysEqual(t, &defaultRequest, res, "RequestedScope", "GrantedScope", "Form", "Session")
err = m.InvalidateAuthorizeCodeSession(ctx, "4321")
require.NoError(t, err)
res, err = m.GetAuthorizeCodeSession(ctx, "4321", &Session{})
require.Error(t, err)
assert.EqualError(t, err, fosite.ErrInvalidatedAuthorizeCode.Error())
assert.NotNil(t, res)
}
}
func testHelperNilAccessToken(x InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
m := x.OAuth2Storage()
c := &client.Client{LegacyClientID: "nil-request-client-id-123"}
require.NoError(t, x.ClientManager().CreateClient(context.Background(), c))
err := m.CreateAccessTokenSession(context.TODO(), "nil-request-id", &fosite.Request{
ID: "",
RequestedAt: time.Now().UTC().Round(time.Second),
Client: c,
RequestedScope: fosite.Arguments{"fa", "ba"},
GrantedScope: fosite.Arguments{"fa", "ba"},
RequestedAudience: fosite.Arguments{"ad1", "ad2"},
GrantedAudience: fosite.Arguments{"ad1", "ad2"},
Form: url.Values{"foo": []string{"bar", "baz"}},
Session: &Session{DefaultSession: &openid.DefaultSession{Subject: "bar"}},
})
require.NoError(t, err)
}
}
func testHelperCreateGetDeleteAccessTokenSession(x InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
m := x.OAuth2Storage()
ctx := context.Background()
_, err := m.GetAccessTokenSession(ctx, "4321", &Session{})
assert.Error(t, err)
err = m.CreateAccessTokenSession(ctx, "4321", &defaultRequest)
require.NoError(t, err)
res, err := m.GetAccessTokenSession(ctx, "4321", &Session{})
require.NoError(t, err)
AssertObjectKeysEqual(t, &defaultRequest, res, "RequestedScope", "GrantedScope", "Form", "Session")
err = m.DeleteAccessTokenSession(ctx, "4321")
require.NoError(t, err)
_, err = m.GetAccessTokenSession(ctx, "4321", &Session{})
assert.Error(t, err)
}
}
func testHelperDeleteAccessTokens(x InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
m := x.OAuth2Storage()
ctx := context.Background()
err := m.CreateAccessTokenSession(ctx, "4321", &defaultRequest)
require.NoError(t, err)
_, err = m.GetAccessTokenSession(ctx, "4321", &Session{})
require.NoError(t, err)
err = m.DeleteAccessTokens(ctx, defaultRequest.Client.GetID())
require.NoError(t, err)
req, err := m.GetAccessTokenSession(ctx, "4321", &Session{})
assert.Nil(t, req)
assert.EqualError(t, err, fosite.ErrNotFound.Error())
}
}
func testHelperRevokeAccessToken(x InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
m := x.OAuth2Storage()
ctx := context.Background()
err := m.CreateAccessTokenSession(ctx, "4321", &defaultRequest)
require.NoError(t, err)
_, err = m.GetAccessTokenSession(ctx, "4321", &Session{})
require.NoError(t, err)
err = m.RevokeAccessToken(ctx, defaultRequest.GetID())
require.NoError(t, err)
req, err := m.GetAccessTokenSession(ctx, "4321", &Session{})
assert.Nil(t, req)
assert.EqualError(t, err, fosite.ErrNotFound.Error())
}
}
func testHelperCreateGetDeletePKCERequestSession(x InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
m := x.OAuth2Storage()
ctx := context.Background()
_, err := m.GetPKCERequestSession(ctx, "4321", &Session{})
assert.NotNil(t, err)
err = m.CreatePKCERequestSession(ctx, "4321", &defaultRequest)
require.NoError(t, err)
res, err := m.GetPKCERequestSession(ctx, "4321", &Session{})
require.NoError(t, err)
AssertObjectKeysEqual(t, &defaultRequest, res, "RequestedScope", "GrantedScope", "Form", "Session")
err = m.DeletePKCERequestSession(ctx, "4321")
require.NoError(t, err)
_, err = m.GetPKCERequestSession(ctx, "4321", &Session{})
assert.NotNil(t, err)
}
}
func testHelperFlushTokens(x InternalRegistry, lifespan time.Duration) func(t *testing.T) {
m := x.OAuth2Storage()
ds := &Session{}
return func(t *testing.T) {
ctx := context.Background()
for _, r := range flushRequests {
mockRequestForeignKey(t, r.ID, x, false)
require.NoError(t, m.CreateAccessTokenSession(ctx, r.ID, r))
_, err := m.GetAccessTokenSession(ctx, r.ID, ds)
require.NoError(t, err)
}
require.NoError(t, m.FlushInactiveAccessTokens(ctx, time.Now().Add(-time.Hour*24), 100, 10))
_, err := m.GetAccessTokenSession(ctx, "flush-1", ds)
require.NoError(t, err)
_, err = m.GetAccessTokenSession(ctx, "flush-2", ds)
require.NoError(t, err)
_, err = m.GetAccessTokenSession(ctx, "flush-3", ds)
require.NoError(t, err)
require.NoError(t, m.FlushInactiveAccessTokens(ctx, time.Now().Add(-(lifespan+time.Hour/2)), 100, 10))
_, err = m.GetAccessTokenSession(ctx, "flush-1", ds)
require.NoError(t, err)
_, err = m.GetAccessTokenSession(ctx, "flush-2", ds)
require.NoError(t, err)
_, err = m.GetAccessTokenSession(ctx, "flush-3", ds)
require.Error(t, err)
require.NoError(t, m.FlushInactiveAccessTokens(ctx, time.Now(), 100, 10))
_, err = m.GetAccessTokenSession(ctx, "flush-1", ds)
require.NoError(t, err)
_, err = m.GetAccessTokenSession(ctx, "flush-2", ds)
require.Error(t, err)
_, err = m.GetAccessTokenSession(ctx, "flush-3", ds)
require.Error(t, err)
require.NoError(t, m.DeleteAccessTokens(ctx, "foobar"))
}
}
func testHelperFlushTokensWithLimitAndBatchSize(x InternalRegistry, limit int, batchSize int) func(t *testing.T) {
m := x.OAuth2Storage()
ds := &Session{}
return func(t *testing.T) {
ctx := context.Background()
var requests []*fosite.Request
// create five expired requests
id := uuid.New()
totalCount := 5
for i := 0; i < totalCount; i++ {
r := createTestRequest(fmt.Sprintf("%s-%d", id, i+1))
r.RequestedAt = time.Now().Add(-2 * time.Hour)
mockRequestForeignKey(t, r.ID, x, false)
require.NoError(t, m.CreateAccessTokenSession(ctx, r.ID, r))
_, err := m.GetAccessTokenSession(ctx, r.ID, ds)
require.NoError(t, err)
requests = append(requests, r)
}
require.NoError(t, m.FlushInactiveAccessTokens(ctx, time.Now(), limit, batchSize))
var notFoundCount, foundCount int
for i := range requests {
if _, err := m.GetAccessTokenSession(ctx, requests[i].ID, ds); err == nil {
foundCount++
} else {
require.ErrorIs(t, err, fosite.ErrNotFound)
notFoundCount++
}
}
assert.Equal(t, limit, notFoundCount, "should have deleted %d tokens", limit)
assert.Equal(t, totalCount-limit, foundCount, "should have found %d tokens", totalCount-limit)
}
}
func testFositeSqlStoreTransactionCommitAccessToken(m InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
{
doTestCommit(m, t, m.OAuth2Storage().CreateAccessTokenSession, m.OAuth2Storage().GetAccessTokenSession, m.OAuth2Storage().RevokeAccessToken)
doTestCommit(m, t, m.OAuth2Storage().CreateAccessTokenSession, m.OAuth2Storage().GetAccessTokenSession, m.OAuth2Storage().DeleteAccessTokenSession)
}
}
}
func testFositeSqlStoreTransactionRollbackAccessToken(m InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
{
doTestRollback(m, t, m.OAuth2Storage().CreateAccessTokenSession, m.OAuth2Storage().GetAccessTokenSession, m.OAuth2Storage().RevokeAccessToken)
doTestRollback(m, t, m.OAuth2Storage().CreateAccessTokenSession, m.OAuth2Storage().GetAccessTokenSession, m.OAuth2Storage().DeleteAccessTokenSession)
}
}
}
func testFositeSqlStoreTransactionCommitRefreshToken(m InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
doTestCommit(m, t, m.OAuth2Storage().CreateRefreshTokenSession, m.OAuth2Storage().GetRefreshTokenSession, m.OAuth2Storage().RevokeRefreshToken)
doTestCommit(m, t, m.OAuth2Storage().CreateRefreshTokenSession, m.OAuth2Storage().GetRefreshTokenSession, m.OAuth2Storage().DeleteRefreshTokenSession)
}
}
func testFositeSqlStoreTransactionRollbackRefreshToken(m InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
doTestRollback(m, t, m.OAuth2Storage().CreateRefreshTokenSession, m.OAuth2Storage().GetRefreshTokenSession, m.OAuth2Storage().RevokeRefreshToken)
doTestRollback(m, t, m.OAuth2Storage().CreateRefreshTokenSession, m.OAuth2Storage().GetRefreshTokenSession, m.OAuth2Storage().DeleteRefreshTokenSession)
}
}
func testFositeSqlStoreTransactionCommitAuthorizeCode(m InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
doTestCommit(m, t, m.OAuth2Storage().CreateAuthorizeCodeSession, m.OAuth2Storage().GetAuthorizeCodeSession, m.OAuth2Storage().InvalidateAuthorizeCodeSession)
}
}
func testFositeSqlStoreTransactionRollbackAuthorizeCode(m InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
doTestRollback(m, t, m.OAuth2Storage().CreateAuthorizeCodeSession, m.OAuth2Storage().GetAuthorizeCodeSession, m.OAuth2Storage().InvalidateAuthorizeCodeSession)
}
}
func testFositeSqlStoreTransactionCommitPKCERequest(m InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
doTestCommit(m, t, m.OAuth2Storage().CreatePKCERequestSession, m.OAuth2Storage().GetPKCERequestSession, m.OAuth2Storage().DeletePKCERequestSession)
}
}
func testFositeSqlStoreTransactionRollbackPKCERequest(m InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
doTestRollback(m, t, m.OAuth2Storage().CreatePKCERequestSession, m.OAuth2Storage().GetPKCERequestSession, m.OAuth2Storage().DeletePKCERequestSession)
}
}
// OpenIdConnect tests can't use the helper functions, due to the signature of GetOpenIdConnectSession being
// different from the other getter methods
func testFositeSqlStoreTransactionCommitOpenIdConnectSession(m InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
txnStore, ok := m.OAuth2Storage().(storage.Transactional)
require.True(t, ok)
ctx := context.Background()
ctx, err := txnStore.BeginTX(ctx)
require.NoError(t, err)
signature := uuid.New()
testRequest := createTestRequest(signature)
err = m.OAuth2Storage().CreateOpenIDConnectSession(ctx, signature, testRequest)
require.NoError(t, err)
err = txnStore.Commit(ctx)
require.NoError(t, err)
// Require a new context, since the old one contains the transaction.
res, err := m.OAuth2Storage().GetOpenIDConnectSession(context.Background(), signature, testRequest)
// session should have been created successfully because Commit did not return an error
require.NoError(t, err)
AssertObjectKeysEqual(t, &defaultRequest, res, "RequestedScope", "GrantedScope", "Form", "Session")
// test delete within a transaction
ctx, err = txnStore.BeginTX(context.Background())
require.NoError(t, err)
err = m.OAuth2Storage().DeleteOpenIDConnectSession(ctx, signature)
require.NoError(t, err)
err = txnStore.Commit(ctx)
require.NoError(t, err)
// Require a new context, since the old one contains the transaction.
_, err = m.OAuth2Storage().GetOpenIDConnectSession(context.Background(), signature, testRequest)
// Since commit worked for delete, we should get an error here.
require.Error(t, err)
}
}
func testFositeSqlStoreTransactionRollbackOpenIdConnectSession(m InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
txnStore, ok := m.OAuth2Storage().(storage.Transactional)
require.True(t, ok)
ctx := context.Background()
ctx, err := txnStore.BeginTX(ctx)
require.NoError(t, err)
signature := uuid.New()
testRequest := createTestRequest(signature)
err = m.OAuth2Storage().CreateOpenIDConnectSession(ctx, signature, testRequest)
require.NoError(t, err)
err = txnStore.Rollback(ctx)
require.NoError(t, err)
// Require a new context, since the old one contains the transaction.
ctx = context.Background()
_, err = m.OAuth2Storage().GetOpenIDConnectSession(ctx, signature, testRequest)
// Since we rolled back above, the session should not exist and getting it should result in an error
require.Error(t, err)
// create a new session, delete it, then rollback the delete. We should be able to then get it.
signature2 := uuid.New()
testRequest2 := createTestRequest(signature2)
err = m.OAuth2Storage().CreateOpenIDConnectSession(ctx, signature2, testRequest2)
require.NoError(t, err)
_, err = m.OAuth2Storage().GetOpenIDConnectSession(ctx, signature2, testRequest2)
require.NoError(t, err)
ctx, err = txnStore.BeginTX(context.Background())
require.NoError(t, err)
err = m.OAuth2Storage().DeleteOpenIDConnectSession(ctx, signature2)
require.NoError(t, err)
err = txnStore.Rollback(ctx)
require.NoError(t, err)
_, err = m.OAuth2Storage().GetOpenIDConnectSession(context.Background(), signature2, testRequest2)
require.NoError(t, err)
}
}
func testFositeStoreSetClientAssertionJWT(m InternalRegistry) func(*testing.T) {
return func(t *testing.T) {
t.Run("case=basic setting works", func(t *testing.T) {
store, ok := m.OAuth2Storage().(AssertionJWTReader)
require.True(t, ok)
jti := NewBlacklistedJTI("basic jti", time.Now().Add(time.Minute))
require.NoError(t, store.SetClientAssertionJWT(context.Background(), jti.JTI, jti.Expiry))
cmp, err := store.GetClientAssertionJWT(context.Background(), jti.JTI)
require.NotEqual(t, cmp.NID, gofrsuuid.Nil)
cmp.NID = gofrsuuid.Nil
require.NoError(t, err)
assert.Equal(t, jti, cmp)
})
t.Run("case=errors when the JTI is blacklisted", func(t *testing.T) {
store, ok := m.OAuth2Storage().(AssertionJWTReader)
require.True(t, ok)
jti := NewBlacklistedJTI("already set jti", time.Now().Add(time.Minute))
require.NoError(t, store.SetClientAssertionJWTRaw(context.Background(), jti))
assert.ErrorIs(t, store.SetClientAssertionJWT(context.Background(), jti.JTI, jti.Expiry), fosite.ErrJTIKnown)
})
t.Run("case=deletes expired JTIs", func(t *testing.T) {
store, ok := m.OAuth2Storage().(AssertionJWTReader)
require.True(t, ok)
expiredJTI := NewBlacklistedJTI("expired jti", time.Now().Add(-time.Minute))
require.NoError(t, store.SetClientAssertionJWTRaw(context.Background(), expiredJTI))
newJTI := NewBlacklistedJTI("some new jti", time.Now().Add(time.Minute))
require.NoError(t, store.SetClientAssertionJWT(context.Background(), newJTI.JTI, newJTI.Expiry))
_, err := store.GetClientAssertionJWT(context.Background(), expiredJTI.JTI)
assert.True(t, errors.Is(err, sqlcon.ErrNoRows))
cmp, err := store.GetClientAssertionJWT(context.Background(), newJTI.JTI)
require.NoError(t, err)
require.NotEqual(t, cmp.NID, gofrsuuid.Nil)
cmp.NID = gofrsuuid.Nil
assert.Equal(t, newJTI, cmp)
})
t.Run("case=inserts same JTI if expired", func(t *testing.T) {
store, ok := m.OAuth2Storage().(AssertionJWTReader)
require.True(t, ok)
jti := NewBlacklistedJTI("going to be reused jti", time.Now().Add(-time.Minute))
require.NoError(t, store.SetClientAssertionJWTRaw(context.Background(), jti))
jti.Expiry = jti.Expiry.Add(2 * time.Minute)
assert.NoError(t, store.SetClientAssertionJWT(context.Background(), jti.JTI, jti.Expiry))
cmp, err := store.GetClientAssertionJWT(context.Background(), jti.JTI)
assert.NoError(t, err)
assert.Equal(t, jti, cmp)
})
}
}
func testFositeStoreClientAssertionJWTValid(m InternalRegistry) func(*testing.T) {
return func(t *testing.T) {
t.Run("case=returns valid on unknown JTI", func(t *testing.T) {
store, ok := m.OAuth2Storage().(AssertionJWTReader)
require.True(t, ok)
assert.NoError(t, store.ClientAssertionJWTValid(context.Background(), "unknown jti"))
})
t.Run("case=returns invalid on known JTI", func(t *testing.T) {
store, ok := m.OAuth2Storage().(AssertionJWTReader)
require.True(t, ok)
jti := NewBlacklistedJTI("known jti", time.Now().Add(time.Minute))
require.NoError(t, store.SetClientAssertionJWTRaw(context.Background(), jti))
assert.True(t, errors.Is(store.ClientAssertionJWTValid(context.Background(), jti.JTI), fosite.ErrJTIKnown))
})
t.Run("case=returns valid on expired JTI", func(t *testing.T) {
store, ok := m.OAuth2Storage().(AssertionJWTReader)
require.True(t, ok)
jti := NewBlacklistedJTI("expired jti 2", time.Now().Add(-time.Minute))
require.NoError(t, store.SetClientAssertionJWTRaw(context.Background(), jti))
assert.NoError(t, store.ClientAssertionJWTValid(context.Background(), jti.JTI))
})
}
}
func testFositeJWTBearerGrantStorage(x InternalRegistry) func(t *testing.T) {
return func(t *testing.T) {
grantManager := x.GrantManager()
keyManager := x.KeyManager()
grantStorage := x.OAuth2Storage().(rfc7523.RFC7523KeyStorage)
t.Run("case=associated key added with grant", func(t *testing.T) {
keySet, err := jwk.GenerateJWK(context.Background(), jose.RS256, "token-service-key", "sig")
require.NoError(t, err)
publicKey := keySet.Keys[0].Public()
issuer := "token-service"
subject := "[email protected]"
grant := trust.Grant{
ID: uuid.New(),
Issuer: issuer,
Subject: subject,
AllowAnySubject: false,
Scope: []string{"openid", "offline"},
PublicKey: trust.PublicKey{Set: issuer, KeyID: publicKey.KeyID},
CreatedAt: time.Now().UTC().Round(time.Second),
ExpiresAt: time.Now().UTC().Round(time.Second).AddDate(1, 0, 0),
}
storedKeySet, err := grantStorage.GetPublicKeys(context.TODO(), issuer, subject)
require.NoError(t, err)
require.Len(t, storedKeySet.Keys, 0)
err = grantManager.CreateGrant(context.TODO(), grant, publicKey)
require.NoError(t, err)
storedKeySet, err = grantStorage.GetPublicKeys(context.TODO(), issuer, subject)
require.NoError(t, err)
assert.Len(t, storedKeySet.Keys, 1)
storedKey, err := grantStorage.GetPublicKey(context.TODO(), issuer, subject, publicKey.KeyID)
require.NoError(t, err)
assert.Equal(t, publicKey.KeyID, storedKey.KeyID)
assert.Equal(t, publicKey.Use, storedKey.Use)
assert.Equal(t, publicKey.Key, storedKey.Key)
storedScopes, err := grantStorage.GetPublicKeyScopes(context.TODO(), issuer, subject, publicKey.KeyID)
require.NoError(t, err)
assert.Equal(t, grant.Scope, storedScopes)
storedKeySet, err = keyManager.GetKey(context.TODO(), issuer, publicKey.KeyID)
require.NoError(t, err)
assert.Equal(t, publicKey.KeyID, storedKeySet.Keys[0].KeyID)
assert.Equal(t, publicKey.Use, storedKeySet.Keys[0].Use)
assert.Equal(t, publicKey.Key, storedKeySet.Keys[0].Key)
})
t.Run("case=only associated key returns", func(t *testing.T) {
keySet, err := jwk.GenerateJWK(context.Background(), jose.RS256, "some-key", "sig")
require.NoError(t, err)
err = keyManager.AddKeySet(context.TODO(), "some-set", keySet)
require.NoError(t, err)
keySet, err = jwk.GenerateJWK(context.Background(), jose.RS256, "maria-key", "sig")
require.NoError(t, err)
publicKey := keySet.Keys[0].Public()
issuer := "maria"
subject := "[email protected]"
grant := trust.Grant{
ID: uuid.New(),
Issuer: issuer,
Subject: subject,
AllowAnySubject: false,
Scope: []string{"openid"},
PublicKey: trust.PublicKey{Set: issuer, KeyID: publicKey.KeyID},
CreatedAt: time.Now().UTC().Round(time.Second),
ExpiresAt: time.Now().UTC().Round(time.Second).AddDate(1, 0, 0),
}
err = grantManager.CreateGrant(context.TODO(), grant, publicKey)
require.NoError(t, err)
storedKeySet, err := grantStorage.GetPublicKeys(context.TODO(), issuer, subject)
require.NoError(t, err)
assert.Len(t, storedKeySet.Keys, 1)
assert.Equal(t, publicKey.KeyID, storedKeySet.Keys[0].KeyID)
assert.Equal(t, publicKey.Use, storedKeySet.Keys[0].Use)
assert.Equal(t, publicKey.Key, storedKeySet.Keys[0].Key)
storedKeySet, err = grantStorage.GetPublicKeys(context.TODO(), issuer, "non-existing-subject")
require.NoError(t, err)
assert.Len(t, storedKeySet.Keys, 0)
_, err = grantStorage.GetPublicKeyScopes(context.TODO(), issuer, "non-existing-subject", publicKey.KeyID)
require.Error(t, err)
})
t.Run("case=associated key is deleted, when granted is deleted", func(t *testing.T) {
keySet, err := jwk.GenerateJWK(context.Background(), jose.RS256, "hackerman-key", "sig")
require.NoError(t, err)
publicKey := keySet.Keys[0].Public()
issuer := "aeneas"
subject := "[email protected]"
grant := trust.Grant{
ID: uuid.New(),
Issuer: issuer,
Subject: subject,
AllowAnySubject: false,
Scope: []string{"openid", "offline"},
PublicKey: trust.PublicKey{Set: issuer, KeyID: publicKey.KeyID},
CreatedAt: time.Now().UTC().Round(time.Second),
ExpiresAt: time.Now().UTC().Round(time.Second).AddDate(1, 0, 0),
}
err = grantManager.CreateGrant(context.TODO(), grant, publicKey)
require.NoError(t, err)
_, err = grantStorage.GetPublicKey(context.TODO(), issuer, subject, grant.PublicKey.KeyID)
require.NoError(t, err)
_, err = keyManager.GetKey(context.TODO(), issuer, publicKey.KeyID)
require.NoError(t, err)
err = grantManager.DeleteGrant(context.TODO(), grant.ID)
require.NoError(t, err)
_, err = grantStorage.GetPublicKey(context.TODO(), issuer, subject, publicKey.KeyID)
assert.Error(t, err)
_, err = keyManager.GetKey(context.TODO(), issuer, publicKey.KeyID)
assert.Error(t, err)
})
t.Run("case=associated grant is deleted, when key is deleted", func(t *testing.T) {
keySet, err := jwk.GenerateJWK(context.Background(), jose.RS256, "vladimir-key", "sig")
require.NoError(t, err)
publicKey := keySet.Keys[0].Public()
issuer := "vladimir"
subject := "[email protected]"
grant := trust.Grant{
ID: uuid.New(),
Issuer: issuer,
Subject: subject,
AllowAnySubject: false,
Scope: []string{"openid", "offline"},
PublicKey: trust.PublicKey{Set: issuer, KeyID: publicKey.KeyID},
CreatedAt: time.Now().UTC().Round(time.Second),
ExpiresAt: time.Now().UTC().Round(time.Second).AddDate(1, 0, 0),
}
err = grantManager.CreateGrant(context.TODO(), grant, publicKey)
require.NoError(t, err)
_, err = grantStorage.GetPublicKey(context.TODO(), issuer, subject, publicKey.KeyID)
require.NoError(t, err)
_, err = keyManager.GetKey(context.TODO(), issuer, publicKey.KeyID)
require.NoError(t, err)
err = keyManager.DeleteKey(context.TODO(), issuer, publicKey.KeyID)
require.NoError(t, err)
_, err = keyManager.GetKey(context.TODO(), issuer, publicKey.KeyID)
assert.Error(t, err)
_, err = grantManager.GetConcreteGrant(context.TODO(), grant.ID)
assert.Error(t, err)
})
t.Run("case=only returns the key when subject matches", func(t *testing.T) {
keySet, err := jwk.GenerateJWK(context.Background(), jose.RS256, "issuer-key", "sig")
require.NoError(t, err)
publicKey := keySet.Keys[0].Public()
issuer := "limited-issuer"
subject := "jagoba"
grant := trust.Grant{
ID: uuid.New(),
Issuer: issuer,
Subject: subject,
AllowAnySubject: false,
Scope: []string{"openid", "offline"},
PublicKey: trust.PublicKey{Set: issuer, KeyID: publicKey.KeyID},
CreatedAt: time.Now().UTC().Round(time.Second),
ExpiresAt: time.Now().UTC().Round(time.Second).AddDate(1, 0, 0),
}
err = grantManager.CreateGrant(context.TODO(), grant, publicKey)
require.NoError(t, err)
// All three get methods should only return the public key when using the valid subject
_, err = grantStorage.GetPublicKey(context.TODO(), issuer, "any-subject-1", publicKey.KeyID)
require.Error(t, err)
_, err = grantStorage.GetPublicKey(context.TODO(), issuer, subject, publicKey.KeyID)
require.NoError(t, err)
_, err = grantStorage.GetPublicKeyScopes(context.TODO(), issuer, "any-subject-2", publicKey.KeyID)
require.Error(t, err)
_, err = grantStorage.GetPublicKeyScopes(context.TODO(), issuer, subject, publicKey.KeyID)
require.NoError(t, err)
jwks, err := grantStorage.GetPublicKeys(context.TODO(), issuer, "any-subject-3")
require.NoError(t, err)
require.NotNil(t, jwks)
require.Empty(t, jwks.Keys)
jwks, err = grantStorage.GetPublicKeys(context.TODO(), issuer, subject)
require.NoError(t, err)
require.NotNil(t, jwks)
require.NotEmpty(t, jwks.Keys)
})
t.Run("case=returns the key when any subject is allowed", func(t *testing.T) {
keySet, err := jwk.GenerateJWK(context.Background(), jose.RS256, "issuer-key", "sig")
require.NoError(t, err)
publicKey := keySet.Keys[0].Public()
issuer := "unlimited-issuer"
grant := trust.Grant{
ID: uuid.New(),
Issuer: issuer,
Subject: "",
AllowAnySubject: true,
Scope: []string{"openid", "offline"},
PublicKey: trust.PublicKey{Set: issuer, KeyID: publicKey.KeyID},
CreatedAt: time.Now().UTC().Round(time.Second),
ExpiresAt: time.Now().UTC().Round(time.Second).AddDate(1, 0, 0),
}
err = grantManager.CreateGrant(context.TODO(), grant, publicKey)
require.NoError(t, err)
// All three get methods should always return the public key
_, err = grantStorage.GetPublicKey(context.TODO(), issuer, "any-subject-1", publicKey.KeyID)
require.NoError(t, err)
_, err = grantStorage.GetPublicKeyScopes(context.TODO(), issuer, "any-subject-2", publicKey.KeyID)
require.NoError(t, err)
jwks, err := grantStorage.GetPublicKeys(context.TODO(), issuer, "any-subject-3")
require.NoError(t, err)
require.NotNil(t, jwks)
require.NotEmpty(t, jwks.Keys)
})
}
}
func doTestCommit(m InternalRegistry, t *testing.T,
createFn func(context.Context, string, fosite.Requester) error,
getFn func(context.Context, string, fosite.Session) (fosite.Requester, error),
revokeFn func(context.Context, string) error,
) {
txnStore, ok := m.OAuth2Storage().(storage.Transactional)
require.True(t, ok)
ctx := context.Background()
ctx, err := txnStore.BeginTX(ctx)
require.NoError(t, err)
signature := uuid.New()
err = createFn(ctx, signature, createTestRequest(signature))
require.NoError(t, err)
err = txnStore.Commit(ctx)
require.NoError(t, err)
// Require a new context, since the old one contains the transaction.
res, err := getFn(context.Background(), signature, &Session{})
// token should have been created successfully because Commit did not return an error
require.NoError(t, err)
AssertObjectKeysEqual(t, &defaultRequest, res, "RequestedScope", "GrantedScope", "Form", "Session")
// testrevoke within a transaction
ctx, err = txnStore.BeginTX(context.Background())
require.NoError(t, err)
err = revokeFn(ctx, signature)
require.NoError(t, err)
err = txnStore.Commit(ctx)
require.NoError(t, err)
// Require a new context, since the old one contains the transaction.
_, err = getFn(context.Background(), signature, &Session{})
// Since commit worked for revoke, we should get an error here.
require.Error(t, err)
}
func doTestRollback(m InternalRegistry, t *testing.T,
createFn func(context.Context, string, fosite.Requester) error,
getFn func(context.Context, string, fosite.Session) (fosite.Requester, error),
revokeFn func(context.Context, string) error,
) {
txnStore, ok := m.OAuth2Storage().(storage.Transactional)
require.True(t, ok)
ctx := context.Background()
ctx, err := txnStore.BeginTX(ctx)
require.NoError(t, err)
signature := uuid.New()
err = createFn(ctx, signature, createTestRequest(signature))
require.NoError(t, err)
err = txnStore.Rollback(ctx)
require.NoError(t, err)
// Require a new context, since the old one contains the transaction.
ctx = context.Background()
_, err = getFn(ctx, signature, &Session{})
// Since we rolled back above, the token should not exist and getting it should result in an error
require.Error(t, err)
// create a new token, revoke it, then rollback the revoke. We should be able to then get it successfully.
signature2 := uuid.New()
err = createFn(ctx, signature2, createTestRequest(signature2))
require.NoError(t, err)
_, err = getFn(ctx, signature2, &Session{})
require.NoError(t, err)
ctx, err = txnStore.BeginTX(context.Background())
require.NoError(t, err)
err = revokeFn(ctx, signature2)
require.NoError(t, err)
err = txnStore.Rollback(ctx)
require.NoError(t, err)
_, err = getFn(context.Background(), signature2, &Session{})
require.NoError(t, err)
}
func createTestRequest(id string) *fosite.Request {
return &fosite.Request{
ID: id,
RequestedAt: time.Now().UTC().Round(time.Second),
Client: &client.Client{LegacyClientID: "foobar"},
RequestedScope: fosite.Arguments{"fa", "ba"},
GrantedScope: fosite.Arguments{"fa", "ba"},
RequestedAudience: fosite.Arguments{"ad1", "ad2"},
GrantedAudience: fosite.Arguments{"ad1", "ad2"},
Form: url.Values{"foo": []string{"bar", "baz"}},
Session: &Session{DefaultSession: &openid.DefaultSession{Subject: "bar"}},
}
} |
Go | hydra/oauth2/fosite_store_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2_test
import (
"context"
"flag"
"testing"
"github.com/stretchr/testify/require"
"github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/driver"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/internal"
. "github.com/ory/hydra/v2/oauth2"
"github.com/ory/x/contextx"
"github.com/ory/x/networkx"
"github.com/ory/x/sqlcon/dockertest"
)
func TestMain(m *testing.M) {
flag.Parse()
defer dockertest.KillAllTestDatabases()
m.Run()
}
var registries = make(map[string]driver.Registry)
var cleanRegistries = func(t *testing.T) {
registries["memory"] = internal.NewRegistryMemory(t, internal.NewConfigurationWithDefaults(), &contextx.Default{})
}
// returns clean registries that can safely be used for one test
// to reuse call cleanRegistries
func setupRegistries(t *testing.T) {
if len(registries) == 0 && !testing.Short() {
// first time called and sql tests
var cleanSQL func(*testing.T)
registries["postgres"], registries["mysql"], registries["cockroach"], cleanSQL = internal.ConnectDatabases(t, true, &contextx.Default{})
cleanMem := cleanRegistries
cleanMem(t)
cleanRegistries = func(t *testing.T) {
cleanMem(t)
cleanSQL(t)
}
} else {
// reset all/init mem
cleanRegistries(t)
}
}
func TestManagers(t *testing.T) {
ctx := context.Background()
tests := []struct {
name string
enableSessionEncrypted bool
}{
{
name: "DisableSessionEncrypted",
enableSessionEncrypted: false,
},
{
name: "EnableSessionEncrypted",
enableSessionEncrypted: true,
},
}
for _, tc := range tests {
t.Run("suite="+tc.name, func(t *testing.T) {
setupRegistries(t)
require.NoError(t, registries["memory"].ClientManager().CreateClient(context.Background(), &client.Client{LegacyClientID: "foobar"})) // this is a workaround because the client is not being created for memory store by test helpers.
for k, store := range registries {
net := &networkx.Network{}
require.NoError(t, store.Persister().Connection(context.Background()).First(net))
store.Config().MustSet(ctx, config.KeyEncryptSessionData, tc.enableSessionEncrypted)
store.WithContextualizer(&contextx.Static{NID: net.ID, C: store.Config().Source(ctx)})
TestHelperRunner(t, store, k)
}
})
}
} |
Go | hydra/oauth2/handler.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2
import (
"encoding/base64"
"encoding/json"
"fmt"
"html/template"
"net/http"
"reflect"
"strings"
"time"
"github.com/tidwall/gjson"
"github.com/pborman/uuid"
"github.com/ory/hydra/v2/x/events"
"github.com/ory/x/httprouterx"
"github.com/ory/x/josex"
jwtV5 "github.com/golang-jwt/jwt/v5"
"github.com/ory/x/errorsx"
"github.com/julienschmidt/httprouter"
"github.com/pkg/errors"
"github.com/ory/fosite"
"github.com/ory/fosite/handler/openid"
"github.com/ory/fosite/token/jwt"
"github.com/ory/x/urlx"
"github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/consent"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/x"
)
const (
DefaultLoginPath = "/oauth2/fallbacks/login"
DefaultConsentPath = "/oauth2/fallbacks/consent"
DefaultPostLogoutPath = "/oauth2/fallbacks/logout/callback"
DefaultLogoutPath = "/oauth2/fallbacks/logout"
DefaultErrorPath = "/oauth2/fallbacks/error"
TokenPath = "/oauth2/token" // #nosec G101
AuthPath = "/oauth2/auth"
LogoutPath = "/oauth2/sessions/logout"
VerifiableCredentialsPath = "/credentials"
UserinfoPath = "/userinfo"
WellKnownPath = "/.well-known/openid-configuration"
JWKPath = "/.well-known/jwks.json"
// IntrospectPath points to the OAuth2 introspection endpoint.
IntrospectPath = "/oauth2/introspect"
RevocationPath = "/oauth2/revoke"
DeleteTokensPath = "/oauth2/tokens" // #nosec G101
)
type Handler struct {
r InternalRegistry
c *config.DefaultProvider
}
func NewHandler(r InternalRegistry, c *config.DefaultProvider) *Handler {
return &Handler{
r: r,
c: c,
}
}
func (h *Handler) SetRoutes(admin *httprouterx.RouterAdmin, public *httprouterx.RouterPublic, corsMiddleware func(http.Handler) http.Handler) {
public.Handler("OPTIONS", TokenPath, corsMiddleware(http.HandlerFunc(h.handleOptions)))
public.Handler("POST", TokenPath, corsMiddleware(http.HandlerFunc(h.oauth2TokenExchange)))
public.GET(AuthPath, h.oAuth2Authorize)
public.POST(AuthPath, h.oAuth2Authorize)
public.GET(LogoutPath, h.performOidcFrontOrBackChannelLogout)
public.POST(LogoutPath, h.performOidcFrontOrBackChannelLogout)
public.GET(DefaultLoginPath, h.fallbackHandler("", "", http.StatusOK, config.KeyLoginURL))
public.GET(DefaultConsentPath, h.fallbackHandler("", "", http.StatusOK, config.KeyConsentURL))
public.GET(DefaultLogoutPath, h.fallbackHandler("", "", http.StatusOK, config.KeyLogoutURL))
public.GET(DefaultPostLogoutPath, h.fallbackHandler(
"You logged out successfully!",
"The Default Post Logout URL is not set which is why you are seeing this fallback page. Your log out request however succeeded.",
http.StatusOK,
config.KeyLogoutRedirectURL,
))
public.GET(DefaultErrorPath, h.DefaultErrorHandler)
public.Handler("OPTIONS", RevocationPath, corsMiddleware(http.HandlerFunc(h.handleOptions)))
public.Handler("POST", RevocationPath, corsMiddleware(http.HandlerFunc(h.revokeOAuth2Token)))
public.Handler("OPTIONS", WellKnownPath, corsMiddleware(http.HandlerFunc(h.handleOptions)))
public.Handler("GET", WellKnownPath, corsMiddleware(http.HandlerFunc(h.discoverOidcConfiguration)))
public.Handler("OPTIONS", UserinfoPath, corsMiddleware(http.HandlerFunc(h.handleOptions)))
public.Handler("GET", UserinfoPath, corsMiddleware(http.HandlerFunc(h.getOidcUserInfo)))
public.Handler("POST", UserinfoPath, corsMiddleware(http.HandlerFunc(h.getOidcUserInfo)))
public.Handler("OPTIONS", VerifiableCredentialsPath, corsMiddleware(http.HandlerFunc(h.handleOptions)))
public.Handler("POST", VerifiableCredentialsPath, corsMiddleware(http.HandlerFunc(h.createVerifiableCredential)))
admin.POST(IntrospectPath, h.introspectOAuth2Token)
admin.DELETE(DeleteTokensPath, h.deleteOAuth2Token)
}
// swagger:route GET /oauth2/sessions/logout oidc revokeOidcSession
//
// # OpenID Connect Front- and Back-channel Enabled Logout
//
// This endpoint initiates and completes user logout at the Ory OAuth2 & OpenID provider and initiates OpenID Connect Front- / Back-channel logout:
//
// - https://openid.net/specs/openid-connect-frontchannel-1_0.html
// - https://openid.net/specs/openid-connect-backchannel-1_0.html
//
// Back-channel logout is performed asynchronously and does not affect logout flow.
//
// Schemes: http, https
//
// Responses:
// 302: emptyResponse
func (h *Handler) performOidcFrontOrBackChannelLogout(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
ctx := r.Context()
handled, err := h.r.ConsentStrategy().HandleOpenIDConnectLogout(ctx, w, r)
if errors.Is(err, consent.ErrAbortOAuth2Request) {
return
} else if err != nil {
x.LogError(r, err, h.r.Logger())
h.forwardError(w, r, err)
return
}
if len(handled.FrontChannelLogoutURLs) == 0 {
http.Redirect(w, r, handled.RedirectTo, http.StatusFound)
return
}
// TODO How are we supposed to test this? Maybe with cypress? #1368
t, err := template.New("logout").Parse(`<html>
<head>
<meta http-equiv="refresh" content="7; URL={{ .RedirectTo }}">
</head>
<style type="text/css">
iframe { position: absolute; left: 0; top: 0; height: 0; width: 0; border: none; }
</style>
<script>
var total = {{ len .FrontChannelLogoutURLs }};
var redir = {{ .RedirectTo }};
var timeouts = [];
var redirected = false;
// Cancel all pending timeouts to avoid to call the frontchannel multiple times.
window.onbeforeunload = () => {
redirected = true;
for (var i=0; i<timeouts.length; i++) {
clearTimeout(timeouts[i]);
}
timeouts = [];
};
function setAndRegisterTimeout(fct, duration) {
if (redirected) {
return;
}
timeouts.push(setTimeout(fct, duration));
}
function redirect() {
window.location.replace(redir);
// In case replace failed try href
setAndRegisterTimeout(function () {
window.location.href = redir;
}, 250);
}
function done() {
total--;
if (total < 1) {
setAndRegisterTimeout(redirect, 500);
}
}
setAndRegisterTimeout(redirect, 7000); // redirect after 7 seconds if e.g. an iframe doesn't load
// If the redirect takes unusually long, show a message
setTimeout(function () {
document.getElementById("redir").style.display = "block";
}, 2000);
</script>
<body>
<noscript>
<p>
JavaScript is disabled - you should be redirected in 5 seconds but if not, click <a
href="{{ .RedirectTo }}">here</a> to continue.
</p>
</noscript>
<p id="redir" style="display: none">
Redirection takes unusually long. If you are not being redirected within the next seconds, click <a href="{{ .RedirectTo }}">here</a> to continue.
</p>
{{ range .FrontChannelLogoutURLs }}<iframe src="{{ . }}" onload="done(this)"></iframe>
{{ end }}
</body>
</html>`)
if err != nil {
x.LogError(r, err, h.r.Logger())
h.forwardError(w, r, err)
return
}
if err := t.Execute(w, handled); err != nil {
x.LogError(r, err, h.r.Logger())
h.forwardError(w, r, err)
return
}
}
// OpenID Connect Discovery Metadata
//
// Includes links to several endpoints (for example `/oauth2/token`) and exposes information on supported signature algorithms
// among others.
//
// swagger:model oidcConfiguration
type oidcConfiguration struct {
// OpenID Connect Issuer URL
//
// An URL using the https scheme with no query or fragment component that the OP asserts as its IssuerURL Identifier.
// If IssuerURL discovery is supported , this value MUST be identical to the issuer value returned
// by WebFinger. This also MUST be identical to the iss Claim value in ID Tokens issued from this IssuerURL.
//
// required: true
// example: https://playground.ory.sh/ory-hydra/public/
Issuer string `json:"issuer"`
// OAuth 2.0 Authorization Endpoint URL
//
// required: true
// example: https://playground.ory.sh/ory-hydra/public/oauth2/auth
AuthURL string `json:"authorization_endpoint"`
// OpenID Connect Dynamic Client Registration Endpoint URL
//
// example: https://playground.ory.sh/ory-hydra/admin/client
RegistrationEndpoint string `json:"registration_endpoint,omitempty"`
// OAuth 2.0 Token Endpoint URL
//
// required: true
// example: https://playground.ory.sh/ory-hydra/public/oauth2/token
TokenURL string `json:"token_endpoint"`
// OpenID Connect Well-Known JSON Web Keys URL
//
// URL of the OP's JSON Web Key Set [JWK] document. This contains the signing key(s) the RP uses to validate
// signatures from the OP. The JWK Set MAY also contain the Server's encryption key(s), which are used by RPs
// to encrypt requests to the Server. When both signing and encryption keys are made available, a use (Key Use)
// parameter value is REQUIRED for all keys in the referenced JWK Set to indicate each key's intended usage.
// Although some algorithms allow the same key to be used for both signatures and encryption, doing so is
// NOT RECOMMENDED, as it is less secure. The JWK x5c parameter MAY be used to provide X.509 representations of
// keys provided. When used, the bare key values MUST still be present and MUST match those in the certificate.
//
// required: true
// example: https://{slug}.projects.oryapis.com/.well-known/jwks.json
JWKsURI string `json:"jwks_uri"`
// OpenID Connect Supported Subject Types
//
// JSON array containing a list of the Subject Identifier types that this OP supports. Valid types include
// pairwise and public.
//
// required: true
// example:
// - public
// - pairwise
SubjectTypes []string `json:"subject_types_supported"`
// OAuth 2.0 Supported Response Types
//
// JSON array containing a list of the OAuth 2.0 response_type values that this OP supports. Dynamic OpenID
// Providers MUST support the code, id_token, and the token id_token Response Type values.
//
// required: true
ResponseTypes []string `json:"response_types_supported"`
// OpenID Connect Supported Claims
//
// JSON array containing a list of the Claim Names of the Claims that the OpenID Provider MAY be able to supply
// values for. Note that for privacy or other reasons, this might not be an exhaustive list.
ClaimsSupported []string `json:"claims_supported"`
// OAuth 2.0 Supported Grant Types
//
// JSON array containing a list of the OAuth 2.0 Grant Type values that this OP supports.
GrantTypesSupported []string `json:"grant_types_supported"`
// OAuth 2.0 Supported Response Modes
//
// JSON array containing a list of the OAuth 2.0 response_mode values that this OP supports.
ResponseModesSupported []string `json:"response_modes_supported"`
// OpenID Connect Userinfo URL
//
// URL of the OP's UserInfo Endpoint.
UserinfoEndpoint string `json:"userinfo_endpoint"`
// OAuth 2.0 Supported Scope Values
//
// JSON array containing a list of the OAuth 2.0 [RFC6749] scope values that this server supports. The server MUST
// support the openid scope value. Servers MAY choose not to advertise some supported scope values even when this parameter is used
ScopesSupported []string `json:"scopes_supported"`
// OAuth 2.0 Supported Client Authentication Methods
//
// JSON array containing a list of Client Authentication methods supported by this Token Endpoint. The options are
// client_secret_post, client_secret_basic, client_secret_jwt, and private_key_jwt, as described in Section 9 of OpenID Connect Core 1.0
TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported"`
// OpenID Connect Supported Userinfo Signing Algorithm
//
// JSON array containing a list of the JWS [JWS] signing algorithms (alg values) [JWA] supported by the UserInfo Endpoint to encode the Claims in a JWT [JWT].
UserinfoSigningAlgValuesSupported []string `json:"userinfo_signing_alg_values_supported"`
// OpenID Connect Supported ID Token Signing Algorithms
//
// JSON array containing a list of the JWS signing algorithms (alg values) supported by the OP for the ID Token
// to encode the Claims in a JWT.
//
// required: true
IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"`
// OpenID Connect Default ID Token Signing Algorithms
//
// Algorithm used to sign OpenID Connect ID Tokens.
//
// required: true
IDTokenSignedResponseAlg []string `json:"id_token_signed_response_alg"`
// OpenID Connect User Userinfo Signing Algorithm
//
// Algorithm used to sign OpenID Connect Userinfo Responses.
//
// required: true
UserinfoSignedResponseAlg []string `json:"userinfo_signed_response_alg"`
// OpenID Connect Request Parameter Supported
//
// Boolean value specifying whether the OP supports use of the request parameter, with true indicating support.
RequestParameterSupported bool `json:"request_parameter_supported"`
// OpenID Connect Request URI Parameter Supported
//
// Boolean value specifying whether the OP supports use of the request_uri parameter, with true indicating support.
RequestURIParameterSupported bool `json:"request_uri_parameter_supported"`
// OpenID Connect Requires Request URI Registration
//
// Boolean value specifying whether the OP requires any request_uri values used to be pre-registered
// using the request_uris registration parameter.
RequireRequestURIRegistration bool `json:"require_request_uri_registration"`
// OpenID Connect Claims Parameter Parameter Supported
//
// Boolean value specifying whether the OP supports use of the claims parameter, with true indicating support.
ClaimsParameterSupported bool `json:"claims_parameter_supported"`
// OAuth 2.0 Token Revocation URL
//
// URL of the authorization server's OAuth 2.0 revocation endpoint.
RevocationEndpoint string `json:"revocation_endpoint"`
// OpenID Connect Back-Channel Logout Supported
//
// Boolean value specifying whether the OP supports back-channel logout, with true indicating support.
BackChannelLogoutSupported bool `json:"backchannel_logout_supported"`
// OpenID Connect Back-Channel Logout Session Required
//
// Boolean value specifying whether the OP can pass a sid (session ID) Claim in the Logout Token to identify the RP
// session with the OP. If supported, the sid Claim is also included in ID Tokens issued by the OP
BackChannelLogoutSessionSupported bool `json:"backchannel_logout_session_supported"`
// OpenID Connect Front-Channel Logout Supported
//
// Boolean value specifying whether the OP supports HTTP-based logout, with true indicating support.
FrontChannelLogoutSupported bool `json:"frontchannel_logout_supported"`
// OpenID Connect Front-Channel Logout Session Required
//
// Boolean value specifying whether the OP can pass iss (issuer) and sid (session ID) query parameters to identify
// the RP session with the OP when the frontchannel_logout_uri is used. If supported, the sid Claim is also
// included in ID Tokens issued by the OP.
FrontChannelLogoutSessionSupported bool `json:"frontchannel_logout_session_supported"`
// OpenID Connect End-Session Endpoint
//
// URL at the OP to which an RP can perform a redirect to request that the End-User be logged out at the OP.
EndSessionEndpoint string `json:"end_session_endpoint"`
// OpenID Connect Supported Request Object Signing Algorithms
//
// JSON array containing a list of the JWS signing algorithms (alg values) supported by the OP for Request Objects,
// which are described in Section 6.1 of OpenID Connect Core 1.0 [OpenID.Core]. These algorithms are used both when
// the Request Object is passed by value (using the request parameter) and when it is passed by reference
// (using the request_uri parameter).
RequestObjectSigningAlgValuesSupported []string `json:"request_object_signing_alg_values_supported"`
// OAuth 2.0 PKCE Supported Code Challenge Methods
//
// JSON array containing a list of Proof Key for Code Exchange (PKCE) [RFC7636] code challenge methods supported
// by this authorization server.
CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported"`
// OpenID Connect Verifiable Credentials Endpoint
//
// Contains the URL of the Verifiable Credentials Endpoint.
CredentialsEndpointDraft00 string `json:"credentials_endpoint_draft_00"`
// OpenID Connect Verifiable Credentials Supported
//
// JSON array containing a list of the Verifiable Credentials supported by this authorization server.
CredentialsSupportedDraft00 []CredentialSupportedDraft00 `json:"credentials_supported_draft_00"`
}
// Verifiable Credentials Metadata (Draft 00)
//
// Includes information about the supported verifiable credentials.
//
// swagger:model credentialSupportedDraft00
type CredentialSupportedDraft00 struct {
// OpenID Connect Verifiable Credentials Format
//
// Contains the format that is supported by this authorization server.
Format string `json:"format"`
// OpenID Connect Verifiable Credentials Types
//
// Contains the types of verifiable credentials supported.
Types []string `json:"types"`
// OpenID Connect Verifiable Credentials Cryptographic Binding Methods Supported
//
// Contains a list of cryptographic binding methods supported for signing the proof.
CryptographicBindingMethodsSupported []string `json:"cryptographic_binding_methods_supported"`
// OpenID Connect Verifiable Credentials Cryptographic Suites Supported
//
// Contains a list of cryptographic suites methods supported for signing the proof.
CryptographicSuitesSupported []string `json:"cryptographic_suites_supported"`
}
// swagger:route GET /.well-known/openid-configuration oidc discoverOidcConfiguration
//
// # OpenID Connect Discovery
//
// A mechanism for an OpenID Connect Relying Party to discover the End-User's OpenID Provider and obtain information needed to interact with it, including its OAuth 2.0 endpoint locations.
//
// Popular libraries for OpenID Connect clients include oidc-client-js (JavaScript), go-oidc (Golang), and others.
// For a full list of clients go here: https://openid.net/developers/certified/
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Responses:
// 200: oidcConfiguration
// default: errorOAuth2
func (h *Handler) discoverOidcConfiguration(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
key, err := h.r.OpenIDJWTStrategy().GetPublicKey(ctx)
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
h.r.Writer().Write(w, r, &oidcConfiguration{
Issuer: h.c.IssuerURL(ctx).String(),
AuthURL: h.c.OAuth2AuthURL(ctx).String(),
TokenURL: h.c.OAuth2TokenURL(ctx).String(),
JWKsURI: h.c.JWKSURL(ctx).String(),
RevocationEndpoint: urlx.AppendPaths(h.c.IssuerURL(ctx), RevocationPath).String(),
RegistrationEndpoint: h.c.OAuth2ClientRegistrationURL(ctx).String(),
SubjectTypes: h.c.SubjectTypesSupported(ctx),
ResponseTypes: []string{"code", "code id_token", "id_token", "token id_token", "token", "token id_token code"},
ClaimsSupported: h.c.OIDCDiscoverySupportedClaims(ctx),
ScopesSupported: h.c.OIDCDiscoverySupportedScope(ctx),
UserinfoEndpoint: h.c.OIDCDiscoveryUserinfoEndpoint(ctx).String(),
TokenEndpointAuthMethodsSupported: []string{"client_secret_post", "client_secret_basic", "private_key_jwt", "none"},
IDTokenSigningAlgValuesSupported: []string{key.Algorithm},
IDTokenSignedResponseAlg: []string{key.Algorithm},
UserinfoSignedResponseAlg: []string{key.Algorithm},
GrantTypesSupported: []string{"authorization_code", "implicit", "client_credentials", "refresh_token"},
ResponseModesSupported: []string{"query", "fragment"},
UserinfoSigningAlgValuesSupported: []string{"none", key.Algorithm},
RequestParameterSupported: true,
RequestURIParameterSupported: true,
RequireRequestURIRegistration: true,
BackChannelLogoutSupported: true,
BackChannelLogoutSessionSupported: true,
FrontChannelLogoutSupported: true,
FrontChannelLogoutSessionSupported: true,
EndSessionEndpoint: urlx.AppendPaths(h.c.IssuerURL(ctx), LogoutPath).String(),
RequestObjectSigningAlgValuesSupported: []string{"none", "RS256", "ES256"},
CodeChallengeMethodsSupported: []string{"plain", "S256"},
CredentialsEndpointDraft00: h.c.CredentialsEndpointURL(ctx).String(),
CredentialsSupportedDraft00: []CredentialSupportedDraft00{{
Format: "jwt_vc_json",
Types: []string{"VerifiableCredential", "UserInfoCredential"},
CryptographicBindingMethodsSupported: []string{"jwk"},
CryptographicSuitesSupported: []string{
"PS256", "RS256", "ES256",
"PS384", "RS384", "ES384",
"PS512", "RS512", "ES512",
"EdDSA",
},
}},
})
}
// OpenID Connect Userinfo
//
// swagger:model oidcUserInfo
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type oidcUserInfo struct {
// Subject - Identifier for the End-User at the IssuerURL.
Subject string `json:"sub"`
// End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences.
Name string `json:"name,omitempty"`
// Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all can be present, with the names being separated by space characters.
GivenName string `json:"given_name,omitempty"`
// Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family name; all can be present, with the names being separated by space characters.
FamilyName string `json:"family_name,omitempty"`
// Middle name(s) of the End-User. Note that in some cultures, people can have multiple middle names; all can be present, with the names being separated by space characters. Also note that in some cultures, middle names are not used.
MiddleName string `json:"middle_name,omitempty"`
// Casual name of the End-User that may or may not be the same as the given_name. For instance, a nickname value of Mike might be returned alongside a given_name value of Michael.
Nickname string `json:"nickname,omitempty"`
// Non-unique shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. This value MAY be any valid JSON string including special characters such as @, /, or whitespace.
PreferredUsername string `json:"preferred_username,omitempty"`
// URL of the End-User's profile page. The contents of this Web page SHOULD be about the End-User.
Profile string `json:"profile,omitempty"`
// URL of the End-User's profile picture. This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file), rather than to a Web page containing an image. Note that this URL SHOULD specifically reference a profile photo of the End-User suitable for displaying when describing the End-User, rather than an arbitrary photo taken by the End-User.
Picture string `json:"picture,omitempty"`
// URL of the End-User's Web page or blog. This Web page SHOULD contain information published by the End-User or an organization that the End-User is affiliated with.
Website string `json:"website,omitempty"`
// End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 [RFC5322] addr-spec syntax. The RP MUST NOT rely upon this value being unique, as discussed in Section 5.7.
Email string `json:"email,omitempty"`
// True if the End-User's e-mail address has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this e-mail address was controlled by the End-User at the time the verification was performed. The means by which an e-mail address is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating.
EmailVerified bool `json:"email_verified,omitempty"`
// End-User's gender. Values defined by this specification are female and male. Other values MAY be used when neither of the defined values are applicable.
Gender string `json:"gender,omitempty"`
// End-User's birthday, represented as an ISO 8601:2004 [ISO8601‑2004] YYYY-MM-DD format. The year MAY be 0000, indicating that it is omitted. To represent only the year, YYYY format is allowed. Note that depending on the underlying platform's date related function, providing just year can result in varying month and day, so the implementers need to take this factor into account to correctly process the dates.
Birthdate string `json:"birthdate,omitempty"`
// String from zoneinfo [zoneinfo] time zone database representing the End-User's time zone. For example, Europe/Paris or America/Los_Angeles.
Zoneinfo string `json:"zoneinfo,omitempty"`
// End-User's locale, represented as a BCP47 [RFC5646] language tag. This is typically an ISO 639-1 Alpha-2 [ISO639‑1] language code in lowercase and an ISO 3166-1 Alpha-2 [ISO3166‑1] country code in uppercase, separated by a dash. For example, en-US or fr-CA. As a compatibility note, some implementations have used an underscore as the separator rather than a dash, for example, en_US; Relying Parties MAY choose to accept this locale syntax as well.
Locale string `json:"locale,omitempty"`
// End-User's preferred telephone number. E.164 [E.164] is RECOMMENDED as the format of this Claim, for example, +1 (425) 555-1212 or +56 (2) 687 2400. If the phone number contains an extension, it is RECOMMENDED that the extension be represented using the RFC 3966 [RFC3966] extension syntax, for example, +1 (604) 555-1234;ext=5678.
PhoneNumber string `json:"phone_number,omitempty"`
// True if the End-User's phone number has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this phone number was controlled by the End-User at the time the verification was performed. The means by which a phone number is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating. When true, the phone_number Claim MUST be in E.164 format and any extensions MUST be represented in RFC 3966 format.
PhoneNumberVerified bool `json:"phone_number_verified,omitempty"`
// Time the End-User's information was last updated. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time.
UpdatedAt int `json:"updated_at,omitempty"`
}
// swagger:route GET /userinfo oidc getOidcUserInfo
//
// # OpenID Connect Userinfo
//
// This endpoint returns the payload of the ID Token, including `session.id_token` values, of
// the provided OAuth 2.0 Access Token's consent request.
//
// In the case of authentication error, a WWW-Authenticate header might be set in the response
// with more information about the error. See [the spec](https://datatracker.ietf.org/doc/html/rfc6750#section-3)
// for more details about header format.
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// oauth2:
//
// Responses:
// 200: oidcUserInfo
// default: errorOAuth2
func (h *Handler) getOidcUserInfo(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session := NewSessionWithCustomClaims(ctx, h.c, "")
tokenType, ar, err := h.r.OAuth2Provider().IntrospectToken(ctx, fosite.AccessTokenFromRequest(r), fosite.AccessToken, session)
if err != nil {
rfcerr := fosite.ErrorToRFC6749Error(err)
if rfcerr.StatusCode() == http.StatusUnauthorized {
w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Bearer error="%s",error_description="%s"`, rfcerr.ErrorField, rfcerr.GetDescription()))
}
h.r.Writer().WriteError(w, r, err)
return
}
if tokenType != fosite.AccessToken {
errorDescription := "Only access tokens are allowed in the authorization header."
w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Bearer error="invalid_token",error_description="%s"`, errorDescription))
h.r.Writer().WriteErrorCode(w, r, http.StatusUnauthorized, errors.New(errorDescription))
return
}
c, ok := ar.GetClient().(*client.Client)
if !ok {
h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrServerError.WithHint("Unable to type assert to *client.Client.")))
return
}
interim := ar.GetSession().(*Session).IDTokenClaims().ToMap()
delete(interim, "nonce")
delete(interim, "at_hash")
delete(interim, "c_hash")
delete(interim, "exp")
delete(interim, "sid")
delete(interim, "jti")
aud, ok := interim["aud"].([]string)
if !ok || len(aud) == 0 {
aud = []string{c.GetID()}
} else {
found := false
for _, a := range aud {
if a == c.GetID() {
found = true
break
}
}
if !found {
aud = append(aud, c.GetID())
}
}
interim["aud"] = aud
if c.UserinfoSignedResponseAlg == "RS256" {
interim["jti"] = uuid.New()
interim["iat"] = time.Now().Unix()
keyID, err := h.r.OpenIDJWTStrategy().GetPublicKeyID(r.Context())
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
token, _, err := h.r.OpenIDJWTStrategy().Generate(ctx, interim, &jwt.Headers{
Extra: map[string]interface{}{"kid": keyID},
})
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
w.Header().Set("Content-Type", "application/jwt")
_, _ = w.Write([]byte(token))
} else if c.UserinfoSignedResponseAlg == "" || c.UserinfoSignedResponseAlg == "none" {
h.r.Writer().Write(w, r, interim)
} else {
h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrServerError.WithHintf("Unsupported userinfo signing algorithm '%s'.", c.UserinfoSignedResponseAlg)))
return
}
}
// Revoke OAuth 2.0 Access or Refresh Token Request
//
// swagger:parameters revokeOAuth2Token
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type revokeOAuth2Token struct {
// in: formData
// required: true
Token string `json:"token"`
// in: formData
ClientID string `json:"client_id"`
// in: formData
ClientSecret string `json:"client_secret"`
}
// swagger:route POST /oauth2/revoke oAuth2 revokeOAuth2Token
//
// # Revoke OAuth 2.0 Access or Refresh Token
//
// Revoking a token (both access and refresh) means that the tokens will be invalid. A revoked access token can no
// longer be used to make access requests, and a revoked refresh token can no longer be used to refresh an access token.
// Revoking a refresh token also invalidates the access token that was created with it. A token may only be revoked by
// the client the token was generated for.
//
// Consumes:
// - application/x-www-form-urlencoded
//
// Schemes: http, https
//
// Security:
// basic:
// oauth2:
//
// Responses:
// 200: emptyResponse
// default: errorOAuth2
func (h *Handler) revokeOAuth2Token(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
events.Trace(r.Context(), events.AccessTokenRevoked)
err := h.r.OAuth2Provider().NewRevocationRequest(ctx, r)
if err != nil {
x.LogError(r, err, h.r.Logger())
}
h.r.OAuth2Provider().WriteRevocationResponse(ctx, w, err)
}
// Introspect OAuth 2.0 Access or Refresh Token Request
//
// swagger:parameters introspectOAuth2Token
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type introspectOAuth2Token struct {
// The string value of the token. For access tokens, this
// is the "access_token" value returned from the token endpoint
// defined in OAuth 2.0. For refresh tokens, this is the "refresh_token"
// value returned.
//
// required: true
// in: formData
Token string `json:"token"`
// An optional, space separated list of required scopes. If the access token was not granted one of the
// scopes, the result of active will be false.
//
// in: formData
Scope string `json:"scope"`
}
// swagger:route POST /admin/oauth2/introspect oAuth2 introspectOAuth2Token
//
// # Introspect OAuth2 Access and Refresh Tokens
//
// The introspection endpoint allows to check if a token (both refresh and access) is active or not. An active token
// is neither expired nor revoked. If a token is active, additional information on the token will be included. You can
// set additional data for a token by setting `session.access_token` during the consent flow.
//
// Consumes:
// - application/x-www-form-urlencoded
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Responses:
// 200: introspectedOAuth2Token
// default: errorOAuth2
func (h *Handler) introspectOAuth2Token(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
ctx := r.Context()
session := NewSessionWithCustomClaims(ctx, h.c, "")
if r.Method != "POST" {
err := errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf("HTTP method is \"%s\", expected \"POST\".", r.Method))
x.LogError(r, err, h.r.Logger())
h.r.OAuth2Provider().WriteIntrospectionError(ctx, w, err)
return
} else if err := r.ParseMultipartForm(1 << 20); err != nil && err != http.ErrNotMultipart {
err := errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Unable to parse HTTP body, make sure to send a properly formatted form request body.").WithDebug(err.Error()))
x.LogError(r, err, h.r.Logger())
h.r.OAuth2Provider().WriteIntrospectionError(ctx, w, err)
return
} else if len(r.PostForm) == 0 {
err := errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("The POST body can not be empty."))
x.LogError(r, err, h.r.Logger())
h.r.OAuth2Provider().WriteIntrospectionError(ctx, w, err)
return
}
token := r.PostForm.Get("token")
tokenType := r.PostForm.Get("token_type_hint")
scope := r.PostForm.Get("scope")
tt, ar, err := h.r.OAuth2Provider().IntrospectToken(ctx, token, fosite.TokenType(tokenType), session, strings.Split(scope, " ")...)
if err != nil {
x.LogAudit(r, err, h.r.Logger())
err := errorsx.WithStack(fosite.ErrInactiveToken.WithHint("An introspection strategy indicated that the token is inactive.").WithDebug(err.Error()))
h.r.OAuth2Provider().WriteIntrospectionError(ctx, w, err)
return
}
resp := &fosite.IntrospectionResponse{
Active: true,
AccessRequester: ar,
TokenUse: tt,
AccessTokenType: "Bearer",
}
exp := resp.GetAccessRequester().GetSession().GetExpiresAt(tt)
if exp.IsZero() {
if tt == fosite.RefreshToken {
exp = resp.GetAccessRequester().GetRequestedAt().Add(h.c.GetRefreshTokenLifespan(ctx))
} else {
exp = resp.GetAccessRequester().GetRequestedAt().Add(h.c.GetAccessTokenLifespan(ctx))
}
}
session, ok := resp.GetAccessRequester().GetSession().(*Session)
if !ok {
err := errorsx.WithStack(fosite.ErrServerError.WithHint("Expected session to be of type *Session, but got another type.").WithDebug(fmt.Sprintf("Got type %s", reflect.TypeOf(resp.GetAccessRequester().GetSession()))))
x.LogError(r, err, h.r.Logger())
h.r.OAuth2Provider().WriteIntrospectionError(ctx, w, err)
return
}
var obfuscated string
if len(session.Claims.Subject) > 0 && session.Claims.Subject != session.Subject {
obfuscated = session.Claims.Subject
}
audience := resp.GetAccessRequester().GetGrantedAudience()
if audience == nil {
// prevent null
audience = fosite.Arguments{}
}
w.Header().Set("Content-Type", "application/json;charset=UTF-8")
if err = json.NewEncoder(w).Encode(&Introspection{
Active: resp.IsActive(),
ClientID: resp.GetAccessRequester().GetClient().GetID(),
Scope: strings.Join(resp.GetAccessRequester().GetGrantedScopes(), " "),
ExpiresAt: exp.Unix(),
IssuedAt: resp.GetAccessRequester().GetRequestedAt().Unix(),
Subject: session.GetSubject(),
Username: session.GetUsername(),
Extra: session.Extra,
Audience: audience,
Issuer: h.c.IssuerURL(ctx).String(),
ObfuscatedSubject: obfuscated,
TokenType: resp.GetAccessTokenType(),
TokenUse: string(resp.GetTokenUse()),
NotBefore: resp.GetAccessRequester().GetRequestedAt().Unix(),
}); err != nil {
x.LogError(r, errorsx.WithStack(err), h.r.Logger())
}
events.Trace(ctx,
events.AccessTokenInspected,
events.WithSubject(session.GetSubject()),
events.WithClientID(resp.GetAccessRequester().GetClient().GetID()),
)
}
// OAuth 2.0 Token Exchange Parameters
//
// swagger:parameters oauth2TokenExchange
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type performOAuth2TokenFlow struct {
// in: formData
// required: true
GrantType string `json:"grant_type"`
// in: formData
Code string `json:"code"`
// in: formData
RefreshToken string `json:"refresh_token"`
// in: formData
RedirectURI string `json:"redirect_uri"`
// in: formData
ClientID string `json:"client_id"`
}
// OAuth2 Token Exchange Result
//
// swagger:model oAuth2TokenExchange
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type oAuth2TokenExchange struct {
// The lifetime in seconds of the access token. For
// example, the value "3600" denotes that the access token will
// expire in one hour from the time the response was generated.
ExpiresIn int `json:"expires_in"`
// The scope of the access token
Scope string `json:"scope"`
// To retrieve a refresh token request the id_token scope.
IDToken int `json:"id_token"`
// The access token issued by the authorization server.
AccessToken string `json:"access_token"`
// The refresh token, which can be used to obtain new
// access tokens. To retrieve it add the scope "offline" to your access token request.
RefreshToken string `json:"refresh_token"`
// The type of the token issued
TokenType string `json:"token_type"`
}
// swagger:route POST /oauth2/token oAuth2 oauth2TokenExchange
//
// # The OAuth 2.0 Token Endpoint
//
// Use open source libraries to perform OAuth 2.0 and OpenID Connect
// available for any programming language. You can find a list of libraries here https://oauth.net/code/
//
// The Ory SDK is not yet able to this endpoint properly.
//
// Consumes:
// - application/x-www-form-urlencoded
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// basic:
// oauth2:
//
// Responses:
// 200: oAuth2TokenExchange
// default: errorOAuth2
func (h *Handler) oauth2TokenExchange(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session := NewSessionWithCustomClaims(ctx, h.c, "")
accessRequest, err := h.r.OAuth2Provider().NewAccessRequest(ctx, r, session)
if err != nil {
h.logOrAudit(err, r)
h.r.OAuth2Provider().WriteAccessError(ctx, w, accessRequest, err)
events.Trace(ctx, events.TokenExchangeError)
return
}
if accessRequest.GetGrantTypes().ExactOne(string(fosite.GrantTypeClientCredentials)) ||
accessRequest.GetGrantTypes().ExactOne(string(fosite.GrantTypeJWTBearer)) {
var accessTokenKeyID string
if h.c.AccessTokenStrategy(ctx, client.AccessTokenStrategySource(accessRequest.GetClient())) == "jwt" {
accessTokenKeyID, err = h.r.AccessTokenJWTStrategy().GetPublicKeyID(ctx)
if err != nil {
x.LogError(r, err, h.r.Logger())
h.r.OAuth2Provider().WriteAccessError(ctx, w, accessRequest, err)
events.Trace(ctx, events.TokenExchangeError, events.WithRequest(accessRequest))
return
}
}
// only for client_credentials, otherwise Authentication is included in session
if accessRequest.GetGrantTypes().ExactOne("client_credentials") {
session.Subject = accessRequest.GetClient().GetID()
}
session.ClientID = accessRequest.GetClient().GetID()
session.KID = accessTokenKeyID
session.DefaultSession.Claims.Issuer = h.c.IssuerURL(r.Context()).String()
session.DefaultSession.Claims.IssuedAt = time.Now().UTC()
scopes := accessRequest.GetRequestedScopes()
// Added for compatibility with MITREid
if h.c.GrantAllClientCredentialsScopesPerDefault(r.Context()) && len(scopes) == 0 {
for _, scope := range accessRequest.GetClient().GetScopes() {
accessRequest.GrantScope(scope)
}
}
for _, scope := range scopes {
if h.r.Config().GetScopeStrategy(ctx)(accessRequest.GetClient().GetScopes(), scope) {
accessRequest.GrantScope(scope)
}
}
for _, audience := range accessRequest.GetRequestedAudience() {
if h.r.AudienceStrategy()(accessRequest.GetClient().GetAudience(), []string{audience}) == nil {
accessRequest.GrantAudience(audience)
}
}
}
for _, hook := range h.r.AccessRequestHooks() {
if err := hook(ctx, accessRequest); err != nil {
h.logOrAudit(err, r)
h.r.OAuth2Provider().WriteAccessError(ctx, w, accessRequest, err)
events.Trace(ctx, events.TokenExchangeError, events.WithRequest(accessRequest))
return
}
}
accessResponse, err := h.r.OAuth2Provider().NewAccessResponse(ctx, accessRequest)
if err != nil {
h.logOrAudit(err, r)
h.r.OAuth2Provider().WriteAccessError(ctx, w, accessRequest, err)
events.Trace(ctx, events.TokenExchangeError, events.WithRequest(accessRequest))
return
}
h.r.OAuth2Provider().WriteAccessResponse(ctx, w, accessRequest, accessResponse)
}
// swagger:route GET /oauth2/auth oAuth2 oAuth2Authorize
//
// # OAuth 2.0 Authorize Endpoint
//
// Use open source libraries to perform OAuth 2.0 and OpenID Connect
// available for any programming language. You can find a list of libraries at https://oauth.net/code/
//
// The Ory SDK is not yet able to this endpoint properly.
//
// Consumes:
// - application/x-www-form-urlencoded
//
// Schemes: http, https
//
// Responses:
// 302: emptyResponse
// default: errorOAuth2
func (h *Handler) oAuth2Authorize(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
ctx := r.Context()
authorizeRequest, err := h.r.OAuth2Provider().NewAuthorizeRequest(ctx, r)
if err != nil {
x.LogError(r, err, h.r.Logger())
h.writeAuthorizeError(w, r, authorizeRequest, err)
return
}
session, flow, err := h.r.ConsentStrategy().HandleOAuth2AuthorizationRequest(ctx, w, r, authorizeRequest)
if errors.Is(err, consent.ErrAbortOAuth2Request) {
x.LogAudit(r, nil, h.r.AuditLogger())
// do nothing
return
} else if e := &(fosite.RFC6749Error{}); errors.As(err, &e) {
x.LogAudit(r, err, h.r.AuditLogger())
h.writeAuthorizeError(w, r, authorizeRequest, err)
return
} else if err != nil {
x.LogError(r, err, h.r.Logger())
h.writeAuthorizeError(w, r, authorizeRequest, err)
return
}
for _, scope := range session.GrantedScope {
authorizeRequest.GrantScope(scope)
}
for _, audience := range session.GrantedAudience {
authorizeRequest.GrantAudience(audience)
}
openIDKeyID, err := h.r.OpenIDJWTStrategy().GetPublicKeyID(ctx)
if err != nil {
x.LogError(r, err, h.r.Logger())
h.writeAuthorizeError(w, r, authorizeRequest, err)
return
}
var accessTokenKeyID string
if h.c.AccessTokenStrategy(r.Context(), client.AccessTokenStrategySource(authorizeRequest.GetClient())) == "jwt" {
accessTokenKeyID, err = h.r.AccessTokenJWTStrategy().GetPublicKeyID(ctx)
if err != nil {
x.LogError(r, err, h.r.Logger())
h.writeAuthorizeError(w, r, authorizeRequest, err)
return
}
}
obfuscatedSubject, err := h.r.ConsentStrategy().ObfuscateSubjectIdentifier(ctx, authorizeRequest.GetClient(), session.ConsentRequest.Subject, session.ConsentRequest.ForceSubjectIdentifier)
if e := &(fosite.RFC6749Error{}); errors.As(err, &e) {
x.LogAudit(r, err, h.r.AuditLogger())
h.writeAuthorizeError(w, r, authorizeRequest, err)
return
} else if err != nil {
x.LogError(r, err, h.r.Logger())
h.writeAuthorizeError(w, r, authorizeRequest, err)
return
}
authorizeRequest.SetID(session.ID)
claims := &jwt.IDTokenClaims{
Subject: obfuscatedSubject,
Issuer: h.c.IssuerURL(ctx).String(),
AuthTime: time.Time(session.AuthenticatedAt),
RequestedAt: session.RequestedAt,
Extra: session.Session.IDToken,
AuthenticationContextClassReference: session.ConsentRequest.ACR,
AuthenticationMethodsReferences: session.ConsentRequest.AMR,
// These are required for work around https://github.com/ory/fosite/issues/530
Nonce: authorizeRequest.GetRequestForm().Get("nonce"),
Audience: []string{authorizeRequest.GetClient().GetID()},
IssuedAt: time.Now().Truncate(time.Second).UTC(),
// This is set by the fosite strategy
// ExpiresAt: time.Now().Add(h.IDTokenLifespan).UTC(),
}
claims.Add("sid", session.ConsentRequest.LoginSessionID)
// done
response, err := h.r.OAuth2Provider().NewAuthorizeResponse(ctx, authorizeRequest, &Session{
DefaultSession: &openid.DefaultSession{
Claims: claims,
Headers: &jwt.Headers{Extra: map[string]interface{}{
// required for lookup on jwk endpoint
"kid": openIDKeyID,
}},
Subject: session.ConsentRequest.Subject,
},
Extra: session.Session.AccessToken,
KID: accessTokenKeyID,
ClientID: authorizeRequest.GetClient().GetID(),
ConsentChallenge: session.ID,
ExcludeNotBeforeClaim: h.c.ExcludeNotBeforeClaim(ctx),
AllowedTopLevelClaims: h.c.AllowedTopLevelClaims(ctx),
MirrorTopLevelClaims: h.c.MirrorTopLevelClaims(ctx),
Flow: flow,
})
if err != nil {
x.LogError(r, err, h.r.Logger())
h.writeAuthorizeError(w, r, authorizeRequest, err)
return
}
h.r.OAuth2Provider().WriteAuthorizeResponse(ctx, w, authorizeRequest, response)
}
// Delete OAuth 2.0 Access Token Parameters
//
// swagger:parameters deleteOAuth2Token
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type deleteOAuth2Token struct {
// OAuth 2.0 Client ID
//
// required: true
// in: query
ClientID string `json:"client_id"`
}
// swagger:route DELETE /admin/oauth2/tokens oAuth2 deleteOAuth2Token
//
// # Delete OAuth 2.0 Access Tokens from specific OAuth 2.0 Client
//
// This endpoint deletes OAuth2 access tokens issued to an OAuth 2.0 Client from the database.
//
// Consumes:
// - application/json
//
// Schemes: http, https
//
// Responses:
// 204: emptyResponse
// default: errorOAuth2
func (h *Handler) deleteOAuth2Token(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
clientID := r.URL.Query().Get("client_id")
if clientID == "" {
h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint(`Query parameter 'client_id' is not defined but it should have been.`)))
return
}
if err := h.r.OAuth2Storage().DeleteAccessTokens(r.Context(), clientID); err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// This function will not be called, OPTIONS request will be handled by cors
// this is just a placeholder.
func (h *Handler) handleOptions(http.ResponseWriter, *http.Request) {}
func (h *Handler) forwardError(w http.ResponseWriter, r *http.Request, err error) {
rfcErr := fosite.ErrorToRFC6749Error(err).WithExposeDebug(h.c.GetSendDebugMessagesToClients(r.Context()))
query := rfcErr.ToValues()
http.Redirect(w, r, urlx.CopyWithQuery(h.c.ErrorURL(r.Context()), query).String(), http.StatusFound)
}
func (h *Handler) writeAuthorizeError(w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester, err error) {
if !ar.IsRedirectURIValid() {
h.forwardError(w, r, err)
return
}
h.r.OAuth2Provider().WriteAuthorizeError(r.Context(), w, ar, err)
}
func (h *Handler) logOrAudit(err error, r *http.Request) {
if errors.Is(err, fosite.ErrServerError) || errors.Is(err, fosite.ErrTemporarilyUnavailable) || errors.Is(err, fosite.ErrMisconfiguration) {
x.LogError(r, err, h.r.Logger())
} else {
x.LogAudit(r, err, h.r.Logger())
}
}
// swagger:route POST /credentials oidc createVerifiableCredential
//
// # Issues a Verifiable Credential
//
// This endpoint creates a verifiable credential that attests that the user
// authenticated with the provided access token owns a certain public/private key
// pair.
//
// More information can be found at
// https://openid.net/specs/openid-connect-userinfo-vc-1_0.html.
//
// Consumes:
// - application/json
//
// Schemes: http, https
//
// Responses:
// 200: verifiableCredentialResponse
// 400: verifiableCredentialPrimingResponse
// default: errorOAuth2
func (h *Handler) createVerifiableCredential(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session := NewSessionWithCustomClaims(ctx, h.c, "")
accessToken := fosite.AccessTokenFromRequest(r)
tokenType, _, err := h.r.OAuth2Provider().IntrospectToken(ctx, accessToken, fosite.AccessToken, session)
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
if tokenType != fosite.AccessToken {
h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf("The provided token is not an access token.")))
return
}
var request CreateVerifiableCredentialRequestBody
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithWrap(err).WithHint("Unable to decode request body.")))
return
}
if request.Format != "jwt_vc_json" {
h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf("The format %q is not supported.", request.Format)))
return
}
if request.Proof == nil {
// Handle priming request
nonceLifespan := h.r.Config().GetVerifiableCredentialsNonceLifespan(ctx)
nonceExpiresIn := time.Now().Add(nonceLifespan).UTC()
nonce, err := h.r.OAuth2Storage().NewNonce(ctx, accessToken, nonceExpiresIn)
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
h.r.Writer().WriteCode(w, r, http.StatusBadRequest, &VerifiableCredentialPrimingResponse{
RFC6749ErrorJson: fosite.RFC6749ErrorJson{
Name: "missing_proof",
Description: "Could not issue a verifiable credential because the proof is missing in the request.",
},
Format: "jwt_vc",
Nonce: nonce,
NonceExpiresIn: int64(nonceLifespan.Seconds()),
})
return
}
if request.Proof.ProofType != "jwt" {
h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf("The proof type %q is not supported.", request.Proof.ProofType)))
return
}
header, _, ok := strings.Cut(request.Proof.JWT, ".")
if !ok {
h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf("The JWT in the proof is malformed.")))
return
}
rawHeader, err := jwtV5.NewParser().DecodeSegment(header)
if err != nil {
h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf("The JWT header in the proof is malformed.")))
return
}
jwk := gjson.GetBytes(rawHeader, "jwk").String()
proofJWK, err := josex.LoadJSONWebKey([]byte(jwk), true)
if err != nil {
h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf("The JWK in the JWT header is malformed.")))
return
}
token, err := jwt.Parse(request.Proof.JWT, func(token *jwt.Token) (any, error) {
return proofJWK, nil
})
if err != nil {
h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf("The JWT was not signed with the correct key supplied in the JWK header.")))
return
}
nonce, ok := token.Claims["nonce"].(string)
if !ok {
h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf(`The JWT did not contain the "nonce" claim.`)))
return
}
if err = h.r.OAuth2Storage().IsNonceValid(ctx, accessToken, nonce); err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
var response VerifiableCredentialResponse
response.Format = "jwt_vc_json"
proofJWKJSON, err := json.Marshal(proofJWK)
if err != nil {
h.r.Writer().WriteError(w, r, errorsx.WithStack(err))
return
}
session.Claims.Add("vc", map[string]any{
"@context": []string{"https://www.w3.org/2018/credentials/v1"},
"type": []string{"VerifiableCredential", "UserInfoCredential"},
"credentialSubject": map[string]any{
// Encode ID according to https://github.com/quartzjer/did-jwk/blob/main/spec.md
"id": fmt.Sprintf("did:jwk:%s", base64.RawURLEncoding.EncodeToString(proofJWKJSON)),
},
})
signingKeyID, err := h.r.OpenIDJWTStrategy().GetPublicKeyID(ctx)
if err != nil {
h.r.Writer().WriteError(w, r, errorsx.WithStack(err))
return
}
headers := jwt.NewHeaders()
headers.Add("kid", signingKeyID)
rawToken, _, err := h.r.OpenIDJWTStrategy().Generate(ctx, session.Claims.ToMapClaims(), headers)
if err != nil {
h.r.Writer().WriteError(w, r, errorsx.WithStack(err))
return
}
response.Credential = rawToken
h.r.Writer().Write(w, r, &response)
}
// Request a Verifiable Credential
//
// swagger:parameters createVerifiableCredential
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type createVerifiableCredentialRequest struct {
// in: body
Body CreateVerifiableCredentialRequestBody
}
// CreateVerifiableCredentialRequestBody contains the request body to request a verifiable credential.
//
// swagger:parameters createVerifiableCredentialRequestBody
type CreateVerifiableCredentialRequestBody struct {
Format string `json:"format"`
Types []string `json:"types"`
Proof *VerifiableCredentialProof `json:"proof"`
}
// VerifiableCredentialProof contains the proof of a verifiable credential.
//
// swagger:parameters verifiableCredentialProof
type VerifiableCredentialProof struct {
ProofType string `json:"proof_type"`
JWT string `json:"jwt"`
}
// VerifiableCredentialResponse contains the verifiable credential.
//
// swagger:model verifiableCredentialResponse
type VerifiableCredentialResponse struct {
Format string `json:"format"`
Credential string `json:"credential_draft_00"`
}
// VerifiableCredentialPrimingResponse contains the nonce to include in the proof-of-possession JWT.
//
// swagger:model verifiableCredentialPrimingResponse
type VerifiableCredentialPrimingResponse struct {
Format string `json:"format"`
Nonce string `json:"c_nonce"`
NonceExpiresIn int64 `json:"c_nonce_expires_in"`
fosite.RFC6749ErrorJson
} |
Go | hydra/oauth2/handler_fallback_endpoints.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2
import (
"html/template"
"net/http"
"github.com/ory/hydra/v2/driver/config"
"github.com/julienschmidt/httprouter"
)
func (h *Handler) fallbackHandler(title, heading string, sc int, configKey string) httprouter.Handle {
if title == "" {
title = "The request could not be executed because a mandatory configuration key is missing or malformed"
}
if heading == "" {
heading = "The request could not be executed because a mandatory configuration key is missing or malformed"
}
return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
h.r.Logger().Errorf(`A request failed because configuration key "%s" is missing or malformed.`, configKey)
t, err := template.New(configKey).Parse(`<html>
<head>
<title>{{ .Title }}</title>
</head>
<body>
<h1>
{{ .Heading }}
</h1>
<p>
You are seeing this page because configuration key <code>{{ .Key }}</code> is not set.
</p>
<p>
If you are an administrator, please read <a href="https://www.ory.sh/docs">the guide</a> to understand what you
need to do. If you are a user, please contact the administrator.
</p>
</body>
</html>`)
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
w.WriteHeader(sc)
if err := t.Execute(w, struct {
Title string
Heading string
Key string
}{Title: title, Heading: heading, Key: configKey}); err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
}
}
func (h *Handler) DefaultErrorHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
h.r.Logger().WithRequest(r).Error("A client requested the default error URL, environment variable URLS_ERROR is probably not set.")
t, err := template.New("consent").Parse(`
<html>
<head>
<title>An OAuth 2.0 Error Occurred</title>
</head>
<body>
<h1>
The OAuth2 request resulted in an error.
</h1>
<ul>
<li>Error: {{ .Name }}</li>
<li>Description: {{ .Description }}</li>
<li>Hint: {{ .Hint }}</li>
<li>Debug: {{ .Debug }}</li>
</ul>
<p>
You are seeing this page because configuration key <code>{{ .Key }}</code> is not set.
</p>
<p>
If you are an administrator, please read <a href="https://www.ory.sh/docs">the guide</a> to understand what you
need to do. If you are a user, please contact the administrator.
</p>
</body>
</html>
`)
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
w.WriteHeader(http.StatusInternalServerError)
if err := t.Execute(w, struct {
Name string
Description string
Hint string
Debug string
Key string
}{
Name: r.URL.Query().Get("error"),
Description: r.URL.Query().Get("error_description"),
Hint: r.URL.Query().Get("error_hint"),
Debug: r.URL.Query().Get("error_debug"),
Key: config.KeyErrorURL,
}); err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
} |
Go | hydra/oauth2/handler_fallback_endpoints_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2_test
import (
"context"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/ory/x/httprouterx"
"github.com/ory/hydra/v2/x"
"github.com/ory/x/contextx"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/internal"
"github.com/ory/hydra/v2/oauth2"
"github.com/stretchr/testify/assert"
)
func TestHandlerConsent(t *testing.T) {
conf := internal.NewConfigurationWithDefaults()
conf.MustSet(context.Background(), config.KeyScopeStrategy, "DEPRECATED_HIERARCHICAL_SCOPE_STRATEGY")
reg := internal.NewRegistryMemory(t, conf, &contextx.Default{})
h := reg.OAuth2Handler()
r := x.NewRouterAdmin(conf.AdminURL)
h.SetRoutes(r, &httprouterx.RouterPublic{Router: r.Router}, func(h http.Handler) http.Handler {
return h
})
ts := httptest.NewServer(r)
defer ts.Close()
res, err := http.Get(ts.URL + oauth2.DefaultConsentPath)
assert.Nil(t, err)
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
assert.Nil(t, err)
assert.NotEmpty(t, body)
} |
Go | hydra/oauth2/handler_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2_test
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
hydra "github.com/ory/hydra-client-go/v2"
"github.com/ory/x/httprouterx"
"github.com/ory/x/snapshotx"
"github.com/ory/x/contextx"
"github.com/ory/hydra/v2/jwk"
"github.com/ory/hydra/v2/x"
"github.com/golang/mock/gomock"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/internal"
"github.com/ory/fosite"
"github.com/ory/fosite/handler/openid"
"github.com/ory/fosite/token/jwt"
"github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/oauth2"
)
var lifespan = time.Hour
func TestHandlerDeleteHandler(t *testing.T) {
ctx := context.Background()
conf := internal.NewConfigurationWithDefaults()
conf.MustSet(ctx, config.KeyIssuerURL, "http://hydra.localhost")
reg := internal.NewRegistryMemory(t, conf, &contextx.Default{})
cm := reg.ClientManager()
store := reg.OAuth2Storage()
h := oauth2.NewHandler(reg, conf)
deleteRequest := &fosite.Request{
ID: "del-1",
RequestedAt: time.Now().Round(time.Second),
Client: &client.Client{LegacyClientID: "foobar"},
RequestedScope: fosite.Arguments{"fa", "ba"},
GrantedScope: fosite.Arguments{"fa", "ba"},
Form: url.Values{"foo": []string{"bar", "baz"}},
Session: &oauth2.Session{DefaultSession: &openid.DefaultSession{Subject: "bar"}},
}
require.NoError(t, cm.CreateClient(context.Background(), deleteRequest.Client.(*client.Client)))
require.NoError(t, store.CreateAccessTokenSession(context.Background(), deleteRequest.ID, deleteRequest))
r := x.NewRouterAdmin(conf.AdminURL)
h.SetRoutes(r, &httprouterx.RouterPublic{Router: r.Router}, func(h http.Handler) http.Handler {
return h
})
ts := httptest.NewServer(r)
defer ts.Close()
c := hydra.NewAPIClient(hydra.NewConfiguration())
c.GetConfig().Servers = hydra.ServerConfigurations{{URL: ts.URL}}
_, err := c.
OAuth2Api.DeleteOAuth2Token(context.Background()).
ClientId("foobar").Execute()
require.NoError(t, err)
ds := new(oauth2.Session)
_, err = store.GetAccessTokenSession(ctx, "del-1", ds)
require.Error(t, err, "not_found")
}
func TestUserinfo(t *testing.T) {
ctx := context.Background()
conf := internal.NewConfigurationWithDefaults()
conf.MustSet(ctx, config.KeyScopeStrategy, "")
conf.MustSet(ctx, config.KeyAuthCodeLifespan, lifespan)
conf.MustSet(ctx, config.KeyIssuerURL, "http://hydra.localhost")
reg := internal.NewRegistryMemory(t, conf, &contextx.Default{})
internal.MustEnsureRegistryKeys(ctx, reg, x.OpenIDConnectKeyName)
ctrl := gomock.NewController(t)
op := NewMockOAuth2Provider(ctrl)
defer ctrl.Finish()
reg.WithOAuth2Provider(op)
h := reg.OAuth2Handler()
router := x.NewRouterAdmin(conf.AdminURL)
h.SetRoutes(router, &httprouterx.RouterPublic{Router: router.Router}, func(h http.Handler) http.Handler {
return h
})
ts := httptest.NewServer(router)
defer ts.Close()
for k, tc := range []struct {
setup func(t *testing.T)
checkForSuccess func(t *testing.T, body []byte)
checkForUnauthorized func(t *testing.T, body []byte, header http.Header)
expectStatusCode int
}{
{
setup: func(t *testing.T) {
op.EXPECT().IntrospectToken(gomock.Any(), gomock.Eq("access-token"), gomock.Eq(fosite.AccessToken), gomock.Any()).Return(fosite.AccessToken, nil, errors.New("asdf"))
},
expectStatusCode: http.StatusInternalServerError,
},
{
setup: func(t *testing.T) {
op.EXPECT().
IntrospectToken(gomock.Any(), gomock.Eq("access-token"), gomock.Eq(fosite.AccessToken), gomock.Any()).
Return(fosite.RefreshToken, nil, nil)
},
checkForUnauthorized: func(t *testing.T, body []byte, headers http.Header) {
assert.True(t, headers.Get("WWW-Authenticate") == `Bearer error="invalid_token",error_description="Only access tokens are allowed in the authorization header."`, "%s", headers)
},
expectStatusCode: http.StatusUnauthorized,
},
{
setup: func(t *testing.T) {
op.EXPECT().
IntrospectToken(gomock.Any(), gomock.Eq("access-token"), gomock.Eq(fosite.AccessToken), gomock.Any()).
Return(fosite.AccessToken, nil, fosite.ErrRequestUnauthorized)
},
checkForUnauthorized: func(t *testing.T, body []byte, headers http.Header) {
assert.True(t, headers.Get("WWW-Authenticate") == `Bearer error="request_unauthorized",error_description="The request could not be authorized. Check that you provided valid credentials in the right format."`, "%s", headers)
},
expectStatusCode: http.StatusUnauthorized,
},
{
setup: func(t *testing.T) {
op.EXPECT().
IntrospectToken(gomock.Any(), gomock.Eq("access-token"), gomock.Eq(fosite.AccessToken), gomock.Any()).
DoAndReturn(func(_ context.Context, _ string, _ fosite.TokenType, _ fosite.Session, _ ...string) (fosite.TokenType, fosite.AccessRequester, error) {
session := &oauth2.Session{
DefaultSession: &openid.DefaultSession{
Claims: &jwt.IDTokenClaims{
Subject: "alice",
},
Headers: new(jwt.Headers),
Subject: "alice",
},
Extra: map[string]interface{}{},
}
return fosite.AccessToken, &fosite.AccessRequest{
Request: fosite.Request{
Client: &client.Client{
LegacyClientID: "foobar",
},
Session: session,
},
}, nil
})
},
expectStatusCode: http.StatusOK,
checkForSuccess: func(t *testing.T, body []byte) {
bodyString := string(body)
assert.True(t, strings.Contains(bodyString, `"sub":"alice"`), "%s", body)
assert.True(t, strings.Contains(bodyString, `"aud":["foobar"]`), "%s", body)
},
},
{
setup: func(t *testing.T) {
op.EXPECT().
IntrospectToken(gomock.Any(), gomock.Eq("access-token"), gomock.Eq(fosite.AccessToken), gomock.Any()).
DoAndReturn(func(_ context.Context, _ string, _ fosite.TokenType, _ fosite.Session, _ ...string) (fosite.TokenType, fosite.AccessRequester, error) {
session := &oauth2.Session{
DefaultSession: &openid.DefaultSession{
Claims: &jwt.IDTokenClaims{
Subject: "another-alice",
Audience: []string{"something-else"},
},
Headers: new(jwt.Headers),
Subject: "alice",
},
Extra: map[string]interface{}{},
}
return fosite.AccessToken, &fosite.AccessRequest{
Request: fosite.Request{
Client: &client.Client{
LegacyClientID: "foobar",
},
Session: session,
},
}, nil
})
},
expectStatusCode: http.StatusOK,
checkForSuccess: func(t *testing.T, body []byte) {
bodyString := string(body)
assert.False(t, strings.Contains(bodyString, `"sub":"alice"`), "%s", body)
assert.True(t, strings.Contains(bodyString, `"sub":"another-alice"`), "%s", body)
assert.True(t, strings.Contains(bodyString, `"aud":["something-else","foobar"]`), "%s", body)
},
},
{
setup: func(t *testing.T) {
op.EXPECT().
IntrospectToken(gomock.Any(), gomock.Eq("access-token"), gomock.Eq(fosite.AccessToken), gomock.Any()).
DoAndReturn(func(_ context.Context, _ string, _ fosite.TokenType, _ fosite.Session, _ ...string) (fosite.TokenType, fosite.AccessRequester, error) {
session := &oauth2.Session{
DefaultSession: &openid.DefaultSession{
Claims: &jwt.IDTokenClaims{
Subject: "alice",
Audience: []string{"foobar"},
},
Headers: new(jwt.Headers),
Subject: "alice",
},
Extra: map[string]interface{}{},
}
return fosite.AccessToken, &fosite.AccessRequest{
Request: fosite.Request{
Client: &client.Client{
LegacyClientID: "foobar",
UserinfoSignedResponseAlg: "none",
},
Session: session,
},
}, nil
})
},
expectStatusCode: http.StatusOK,
checkForSuccess: func(t *testing.T, body []byte) {
bodyString := string(body)
assert.True(t, strings.Contains(bodyString, `"sub":"alice"`), "%s", body)
assert.True(t, strings.Contains(bodyString, `"aud":["foobar"]`), "%s", body)
},
},
{
setup: func(t *testing.T) {
op.EXPECT().
IntrospectToken(gomock.Any(), gomock.Eq("access-token"), gomock.Eq(fosite.AccessToken), gomock.Any()).
DoAndReturn(func(_ context.Context, _ string, _ fosite.TokenType, _ fosite.Session, _ ...string) (fosite.TokenType, fosite.AccessRequester, error) {
session := &oauth2.Session{
DefaultSession: &openid.DefaultSession{
Claims: &jwt.IDTokenClaims{
Subject: "alice",
},
Headers: new(jwt.Headers),
Subject: "alice",
},
Extra: map[string]interface{}{},
}
return fosite.AccessToken, &fosite.AccessRequest{
Request: fosite.Request{
Client: &client.Client{
UserinfoSignedResponseAlg: "asdfasdf",
},
Session: session,
},
}, nil
})
},
expectStatusCode: http.StatusInternalServerError,
},
{
setup: func(t *testing.T) {
op.EXPECT().
IntrospectToken(gomock.Any(), gomock.Eq("access-token"), gomock.Eq(fosite.AccessToken), gomock.Any()).
DoAndReturn(func(_ context.Context, _ string, _ fosite.TokenType, _ fosite.Session, _ ...string) (fosite.TokenType, fosite.AccessRequester, error) {
session := &oauth2.Session{
DefaultSession: &openid.DefaultSession{
Claims: &jwt.IDTokenClaims{
Subject: "alice",
},
Headers: new(jwt.Headers),
Subject: "alice",
},
Extra: map[string]interface{}{},
}
return fosite.AccessToken, &fosite.AccessRequest{
Request: fosite.Request{
Client: &client.Client{
LegacyClientID: "foobar-client",
UserinfoSignedResponseAlg: "RS256",
},
Session: session,
},
}, nil
})
},
expectStatusCode: http.StatusOK,
checkForSuccess: func(t *testing.T, body []byte) {
claims, err := jwt.Parse(string(body), func(token *jwt.Token) (interface{}, error) {
keys, err := reg.KeyManager().GetKeySet(context.Background(), x.OpenIDConnectKeyName)
require.NoError(t, err)
t.Logf("%+v", keys)
key, _ := jwk.FindPublicKey(keys)
return key.Key, nil
})
require.NoError(t, err)
assert.EqualValues(t, "alice", claims.Claims["sub"])
assert.EqualValues(t, []interface{}{"foobar-client"}, claims.Claims["aud"], "%#v", claims.Claims)
assert.NotEmpty(t, claims.Claims["jti"])
},
},
} {
t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) {
tc.setup(t)
req, err := http.NewRequest("GET", ts.URL+"/userinfo", nil)
require.NoError(t, err)
req.Header.Set("Authorization", "Bearer access-token")
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
require.EqualValues(t, tc.expectStatusCode, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
if tc.expectStatusCode == http.StatusOK {
tc.checkForSuccess(t, body)
} else if tc.expectStatusCode == http.StatusUnauthorized {
tc.checkForUnauthorized(t, body, resp.Header)
}
})
}
}
func TestHandlerWellKnown(t *testing.T) {
ctx := context.Background()
conf := internal.NewConfigurationWithDefaults()
t.Run(fmt.Sprintf("hsm_enabled=%v", conf.HSMEnabled()), func(t *testing.T) {
conf.MustSet(ctx, config.KeyScopeStrategy, "DEPRECATED_HIERARCHICAL_SCOPE_STRATEGY")
conf.MustSet(ctx, config.KeyIssuerURL, "http://hydra.localhost")
conf.MustSet(ctx, config.KeySubjectTypesSupported, []string{"pairwise", "public"})
conf.MustSet(ctx, config.KeyOIDCDiscoverySupportedClaims, []string{"sub"})
conf.MustSet(ctx, config.KeyOAuth2ClientRegistrationURL, "http://client-register/registration")
conf.MustSet(ctx, config.KeyOIDCDiscoveryUserinfoEndpoint, "/userinfo")
reg := internal.NewRegistryMemory(t, conf, &contextx.Default{})
h := oauth2.NewHandler(reg, conf)
r := x.NewRouterAdmin(conf.AdminURL)
h.SetRoutes(r, &httprouterx.RouterPublic{Router: r.Router}, func(h http.Handler) http.Handler {
return h
})
ts := httptest.NewServer(r)
defer ts.Close()
res, err := http.Get(ts.URL + "/.well-known/openid-configuration")
require.NoError(t, err)
defer res.Body.Close()
var wellKnownResp hydra.OidcConfiguration
err = json.NewDecoder(res.Body).Decode(&wellKnownResp)
require.NoError(t, err, "problem decoding wellknown json response: %+v", err)
snapshotx.SnapshotT(t, wellKnownResp)
})
} |
Go | hydra/oauth2/helper_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2_test
import (
"context"
"github.com/ory/fosite"
"github.com/ory/fosite/handler/oauth2"
"github.com/ory/fosite/token/hmac"
)
func Tokens(c fosite.Configurator, length int) (res [][]string) {
s := &oauth2.HMACSHAStrategy{Enigma: &hmac.HMACStrategy{Config: c}, Config: c}
for i := 0; i < length; i++ {
tok, sig, _ := s.Enigma.Generate(context.Background())
res = append(res, []string{sig, tok})
}
return res
} |
Go | hydra/oauth2/introspector.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2
// Introspection contains an access token's session data as specified by
// [IETF RFC 7662](https://tools.ietf.org/html/rfc7662)
//
// swagger:model introspectedOAuth2Token
type Introspection struct {
// Active is a boolean indicator of whether or not the presented token
// is currently active. The specifics of a token's "active" state
// will vary depending on the implementation of the authorization
// server and the information it keeps about its tokens, but a "true"
// value return for the "active" property will generally indicate
// that a given token has been issued by this authorization server,
// has not been revoked by the resource owner, and is within its
// given time window of validity (e.g., after its issuance time and
// before its expiration time).
//
// required: true
Active bool `json:"active"`
// Scope is a JSON string containing a space-separated list of
// scopes associated with this token.
Scope string `json:"scope,omitempty"`
// ID is aclient identifier for the OAuth 2.0 client that
// requested this token.
ClientID string `json:"client_id"`
// Subject of the token, as defined in JWT [RFC7519].
// Usually a machine-readable identifier of the resource owner who
// authorized this token.
Subject string `json:"sub"`
// ObfuscatedSubject is set when the subject identifier algorithm was set to "pairwise" during authorization.
// It is the `sub` value of the ID Token that was issued.
ObfuscatedSubject string `json:"obfuscated_subject,omitempty"`
// Expires at is an integer timestamp, measured in the number of seconds
// since January 1 1970 UTC, indicating when this token will expire.
ExpiresAt int64 `json:"exp"`
// Issued at is an integer timestamp, measured in the number of seconds
// since January 1 1970 UTC, indicating when this token was
// originally issued.
IssuedAt int64 `json:"iat"`
// NotBefore is an integer timestamp, measured in the number of seconds
// since January 1 1970 UTC, indicating when this token is not to be
// used before.
NotBefore int64 `json:"nbf"`
// Username is a human-readable identifier for the resource owner who
// authorized this token.
Username string `json:"username,omitempty"`
// Audience contains a list of the token's intended audiences.
Audience []string `json:"aud"`
// IssuerURL is a string representing the issuer of this token
Issuer string `json:"iss"`
// TokenType is the introspected token's type, typically `Bearer`.
TokenType string `json:"token_type"`
// TokenUse is the introspected token's use, for example `access_token` or `refresh_token`.
TokenUse string `json:"token_use"`
// Extra is arbitrary data set by the session.
Extra map[string]interface{} `json:"ext,omitempty"`
} |
Go | hydra/oauth2/introspector_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2_test
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
hydra "github.com/ory/hydra-client-go/v2"
"github.com/ory/x/httprouterx"
"github.com/ory/hydra/v2/x"
"github.com/ory/x/contextx"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/internal"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/ory/fosite"
)
func TestIntrospectorSDK(t *testing.T) {
ctx := context.Background()
conf := internal.NewConfigurationWithDefaults()
conf.MustSet(ctx, config.KeyScopeStrategy, "wildcard")
conf.MustSet(ctx, config.KeyIssuerURL, "https://foobariss")
reg := internal.NewRegistryMemory(t, conf, &contextx.Default{})
internal.MustEnsureRegistryKeys(ctx, reg, x.OpenIDConnectKeyName)
internal.AddFositeExamples(reg)
tokens := Tokens(reg.OAuth2ProviderConfig(), 4)
c, err := reg.ClientManager().GetConcreteClient(context.TODO(), "my-client")
require.NoError(t, err)
c.Scope = "fosite,openid,photos,offline,foo.*"
require.NoError(t, reg.ClientManager().UpdateClient(context.TODO(), c))
router := x.NewRouterAdmin(conf.AdminURL)
handler := reg.OAuth2Handler()
handler.SetRoutes(router, &httprouterx.RouterPublic{Router: router.Router}, func(h http.Handler) http.Handler {
return h
})
server := httptest.NewServer(router)
defer server.Close()
now := time.Now().UTC().Round(time.Minute)
createAccessTokenSession("alice", "my-client", tokens[0][0], now.Add(time.Hour), reg.OAuth2Storage(), fosite.Arguments{"core", "foo.*"})
createAccessTokenSession("siri", "my-client", tokens[1][0], now.Add(-time.Hour), reg.OAuth2Storage(), fosite.Arguments{"core", "foo.*"})
createAccessTokenSession("my-client", "my-client", tokens[2][0], now.Add(time.Hour), reg.OAuth2Storage(), fosite.Arguments{"hydra.introspect"})
createAccessTokenSessionPairwise("alice", "my-client", tokens[3][0], now.Add(time.Hour), reg.OAuth2Storage(), fosite.Arguments{"core", "foo.*"}, "alice-obfuscated")
t.Run("TestIntrospect", func(t *testing.T) {
for k, c := range []struct {
token string
description string
expectInactive bool
scopes []string
assert func(*testing.T, *hydra.IntrospectedOAuth2Token)
prepare func(*testing.T) *hydra.APIClient
}{
{
description: "should fail because invalid token was supplied",
token: "invalid",
expectInactive: true,
},
{
description: "should fail because token is expired",
token: tokens[1][1],
expectInactive: true,
},
// {
// description: "should fail because username / password are invalid",
// token: tokens[0][1],
// expectInactive: true,
// expectCode: http.StatusUnauthorized,
// prepare: func(*testing.T) *hydra.OAuth2Api.{
// client := hydra.Ne.OAuth2Api.ithBasePath(server.URL)
// client.config.Username = "foo"
// client.config.Password = "foo"
// return client
// },
// },
{
description: "should fail because scope `bar` was requested but only `foo` is granted",
token: tokens[0][1],
expectInactive: true,
scopes: []string{"bar"},
},
{
description: "should pass",
token: tokens[0][1],
expectInactive: false,
},
{
description: "should pass using bearer authorization",
token: tokens[0][1],
expectInactive: false,
scopes: []string{"foo.bar"},
assert: func(t *testing.T, c *hydra.IntrospectedOAuth2Token) {
assert.Equal(t, "alice", *c.Sub)
assert.Equal(t, now.Add(time.Hour).Unix(), *c.Exp, "expires at")
assert.Equal(t, now.Unix(), *c.Iat, "issued at")
assert.Equal(t, "https://foobariss", *c.Iss, "issuer")
assert.Equal(t, map[string]interface{}{"foo": "bar"}, c.Ext)
},
},
{
description: "should pass using regular authorization",
token: tokens[0][1],
expectInactive: false,
scopes: []string{"foo.bar"},
assert: func(t *testing.T, c *hydra.IntrospectedOAuth2Token) {
assert.Equal(t, "core foo.*", *c.Scope)
assert.Equal(t, "alice", *c.Sub)
assert.Equal(t, now.Add(time.Hour).Unix(), *c.Exp, "expires at")
assert.Equal(t, now.Unix(), *c.Iat, "issued at")
assert.Equal(t, "https://foobariss", *c.Iss, "issuer")
assert.Equal(t, map[string]interface{}{"foo": "bar"}, c.Ext)
},
},
{
description: "should pass and check for obfuscated subject",
token: tokens[3][1],
expectInactive: false,
scopes: []string{"foo.bar"},
assert: func(t *testing.T, c *hydra.IntrospectedOAuth2Token) {
assert.Equal(t, "alice", *c.Sub)
assert.Equal(t, "alice-obfuscated", *c.ObfuscatedSubject)
},
},
} {
t.Run(fmt.Sprintf("case=%d/description=%s", k, c.description), func(t *testing.T) {
var client *hydra.APIClient
if c.prepare != nil {
client = c.prepare(t)
} else {
client = hydra.NewAPIClient(hydra.NewConfiguration())
client.GetConfig().Servers = hydra.ServerConfigurations{{URL: server.URL}}
}
ctx, _, err := client.OAuth2Api.IntrospectOAuth2Token(context.Background()).
Token(c.token).Scope(strings.Join(c.scopes, " ")).Execute()
require.NoError(t, err)
if c.expectInactive {
assert.False(t, ctx.Active)
} else {
assert.True(t, ctx.Active)
}
if !c.expectInactive && c.assert != nil {
c.assert(t, ctx)
}
})
}
})
} |
Go | hydra/oauth2/oauth2_auth_code_bench_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2_test
import (
"context"
"flag"
"net/http"
"os"
"runtime"
"runtime/pprof"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/go-jose/go-jose/v3"
"github.com/pborman/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
"go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
semconv "go.opentelemetry.io/otel/semconv/v1.12.0"
"golang.org/x/oauth2"
hydra "github.com/ory/hydra-client-go/v2"
hc "github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/internal"
"github.com/ory/hydra/v2/internal/testhelpers"
"github.com/ory/hydra/v2/jwk"
"github.com/ory/hydra/v2/x"
"github.com/ory/x/contextx"
"github.com/ory/x/pointerx"
"github.com/ory/x/stringsx"
)
var (
prof = flag.String("profile", "", "write a CPU profile to this filename")
conc = flag.Int("conc", 100, "dispatch this many requests concurrently")
tracing = flag.Bool("tracing", false, "send OpenTelemetry traces to localhost:4318")
)
func BenchmarkAuthCode(b *testing.B) {
flag.Parse()
ctx := context.Background()
spans := tracetest.NewSpanRecorder()
opts := []trace.TracerProviderOption{
trace.WithSpanProcessor(spans),
trace.WithResource(resource.NewWithAttributes(
semconv.SchemaURL, attribute.String(string(semconv.ServiceNameKey), "BenchmarkAuthCode"),
)),
}
if *tracing {
exporter, err := otlptracehttp.New(ctx, otlptracehttp.WithInsecure(), otlptracehttp.WithEndpoint("localhost:4318"))
require.NoError(b, err)
opts = append(opts, trace.WithSpanProcessor(trace.NewSimpleSpanProcessor(exporter)))
}
provider := trace.NewTracerProvider(opts...)
tracer := provider.Tracer("BenchmarkAuthCode")
otel.SetTextMapPropagator(propagation.TraceContext{})
otel.SetTracerProvider(provider)
ctx, span := tracer.Start(ctx, "BenchmarkAuthCode")
defer span.End()
ctx = context.WithValue(ctx, oauth2.HTTPClient, otelhttp.DefaultClient)
dsn := stringsx.Coalesce(os.Getenv("DSN"), "postgres://postgres:[email protected]:3445/postgres?sslmode=disable&max_conns=20&max_idle_conns=20")
// dsn := "mysql://root:secret@tcp(localhost:3444)/mysql?max_conns=16&max_idle_conns=16"
// dsn := "cockroach://root@localhost:3446/defaultdb?sslmode=disable&max_conns=16&max_idle_conns=16"
reg := internal.NewRegistrySQLFromURL(b, dsn, true, new(contextx.Default)).WithTracer(tracer)
reg.Config().MustSet(ctx, config.KeyLogLevel, "error")
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, "opaque")
reg.Config().MustSet(ctx, config.KeyRefreshTokenHookURL, "")
oauth2Keys, err := jwk.GenerateJWK(ctx, jose.ES256, x.OAuth2JWTKeyName, "sig")
require.NoError(b, err)
oidcKeys, err := jwk.GenerateJWK(ctx, jose.ES256, x.OpenIDConnectKeyName, "sig")
require.NoError(b, err)
_, _ = oauth2Keys, oidcKeys
require.NoError(b, reg.KeyManager().UpdateKeySet(ctx, x.OAuth2JWTKeyName, oauth2Keys))
require.NoError(b, reg.KeyManager().UpdateKeySet(ctx, x.OpenIDConnectKeyName, oidcKeys))
_, adminTS := testhelpers.NewOAuth2Server(ctx, b, reg)
var (
authURL = reg.Config().OAuth2AuthURL(ctx).String()
tokenURL = reg.Config().OAuth2TokenURL(ctx).String()
nonce = uuid.New()
)
newOAuth2Client := func(b *testing.B, cb string) (*hc.Client, *oauth2.Config) {
secret := uuid.New()
c := &hc.Client{
Secret: secret,
RedirectURIs: []string{cb},
ResponseTypes: []string{"id_token", "code", "token"},
GrantTypes: []string{"implicit", "refresh_token", "authorization_code", "password", "client_credentials"},
Scope: "hydra offline openid",
Audience: []string{"https://api.ory.sh/"},
}
require.NoError(b, reg.ClientManager().CreateClient(ctx, c))
return c, &oauth2.Config{
ClientID: c.GetID(),
ClientSecret: secret,
Endpoint: oauth2.Endpoint{
AuthURL: authURL,
TokenURL: tokenURL,
AuthStyle: oauth2.AuthStyleInHeader,
},
Scopes: strings.Split(c.Scope, " "),
}
}
cfg := hydra.NewConfiguration()
cfg.HTTPClient = otelhttp.DefaultClient
adminClient := hydra.NewAPIClient(cfg)
adminClient.GetConfig().Servers = hydra.ServerConfigurations{{URL: adminTS.URL}}
getAuthorizeCode := func(ctx context.Context, b *testing.B, conf *oauth2.Config, c *http.Client, params ...oauth2.AuthCodeOption) (string, *http.Response) {
if c == nil {
c = testhelpers.NewEmptyJarClient(b)
}
state := uuid.New()
req, err := http.NewRequestWithContext(ctx, "GET", conf.AuthCodeURL(state, params...), nil)
require.NoError(b, err)
resp, err := c.Do(req)
require.NoError(b, err)
defer resp.Body.Close()
q := resp.Request.URL.Query()
require.EqualValues(b, state, q.Get("state"))
return q.Get("code"), resp
}
acceptLoginHandler := func(b *testing.B, c *hc.Client, checkRequestPayload func(request *hydra.OAuth2LoginRequest) *hydra.AcceptOAuth2LoginRequest) http.HandlerFunc {
return otelhttp.NewHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
rr, _, err := adminClient.OAuth2Api.GetOAuth2LoginRequest(ctx).LoginChallenge(r.URL.Query().Get("login_challenge")).Execute()
require.NoError(b, err)
assert.EqualValues(b, c.GetID(), pointerx.Deref(rr.Client.ClientId))
assert.Empty(b, pointerx.Deref(rr.Client.ClientSecret))
assert.EqualValues(b, c.GrantTypes, rr.Client.GrantTypes)
assert.EqualValues(b, c.LogoURI, pointerx.Deref(rr.Client.LogoUri))
assert.EqualValues(b, c.RedirectURIs, rr.Client.RedirectUris)
assert.EqualValues(b, r.URL.Query().Get("login_challenge"), rr.Challenge)
assert.EqualValues(b, []string{"hydra", "offline", "openid"}, rr.RequestedScope)
assert.Contains(b, rr.RequestUrl, authURL)
acceptBody := hydra.AcceptOAuth2LoginRequest{
Subject: uuid.New(),
Remember: pointerx.Ptr(!rr.Skip),
Acr: pointerx.Ptr("1"),
Amr: []string{"pwd"},
Context: map[string]interface{}{"context": "bar"},
}
if checkRequestPayload != nil {
if b := checkRequestPayload(rr); b != nil {
acceptBody = *b
}
}
v, _, err := adminClient.OAuth2Api.AcceptOAuth2LoginRequest(ctx).
LoginChallenge(r.URL.Query().Get("login_challenge")).
AcceptOAuth2LoginRequest(acceptBody).
Execute()
require.NoError(b, err)
require.NotEmpty(b, v.RedirectTo)
http.Redirect(w, r, v.RedirectTo, http.StatusFound)
}), "acceptLoginHandler").ServeHTTP
}
acceptConsentHandler := func(b *testing.B, c *hc.Client, checkRequestPayload func(*hydra.OAuth2ConsentRequest)) http.HandlerFunc {
return otelhttp.NewHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
rr, _, err := adminClient.OAuth2Api.GetOAuth2ConsentRequest(ctx).ConsentChallenge(r.URL.Query().Get("consent_challenge")).Execute()
require.NoError(b, err)
assert.EqualValues(b, c.GetID(), pointerx.Deref(rr.Client.ClientId))
assert.Empty(b, pointerx.Deref(rr.Client.ClientSecret))
assert.EqualValues(b, c.GrantTypes, rr.Client.GrantTypes)
assert.EqualValues(b, c.LogoURI, pointerx.Deref(rr.Client.LogoUri))
assert.EqualValues(b, c.RedirectURIs, rr.Client.RedirectUris)
// assert.EqualValues(b, subject, pointerx.Deref(rr.Subject))
assert.EqualValues(b, []string{"hydra", "offline", "openid"}, rr.RequestedScope)
assert.EqualValues(b, r.URL.Query().Get("consent_challenge"), rr.Challenge)
assert.Contains(b, *rr.RequestUrl, authURL)
if checkRequestPayload != nil {
checkRequestPayload(rr)
}
assert.Equal(b, map[string]interface{}{"context": "bar"}, rr.Context)
v, _, err := adminClient.OAuth2Api.AcceptOAuth2ConsentRequest(ctx).
ConsentChallenge(r.URL.Query().Get("consent_challenge")).
AcceptOAuth2ConsentRequest(hydra.AcceptOAuth2ConsentRequest{
GrantScope: []string{"hydra", "offline", "openid"}, Remember: pointerx.Ptr(true), RememberFor: pointerx.Ptr[int64](0),
GrantAccessTokenAudience: rr.RequestedAccessTokenAudience,
Session: &hydra.AcceptOAuth2ConsentRequestSession{
AccessToken: map[string]interface{}{"foo": "bar"},
IdToken: map[string]interface{}{"bar": "baz"},
},
}).
Execute()
require.NoError(b, err)
require.NotEmpty(b, v.RedirectTo)
http.Redirect(w, r, v.RedirectTo, http.StatusFound)
}), "acceptConsentHandler").ServeHTTP
}
run := func(b *testing.B, strategy string) func(*testing.B) {
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
c, conf := newOAuth2Client(b, testhelpers.NewCallbackURL(b, "callback", testhelpers.HTTPServerNotImplementedHandler))
testhelpers.NewLoginConsentUI(b, reg.Config(),
acceptLoginHandler(b, c, nil),
acceptConsentHandler(b, c, nil),
)
return func(b *testing.B) {
//pop.Debug = true
code, _ := getAuthorizeCode(ctx, b, conf, nil, oauth2.SetAuthURLParam("nonce", nonce))
require.NotEmpty(b, code)
_, err := conf.Exchange(ctx, code)
//pop.Debug = false
require.NoError(b, err)
}
}
b.ResetTimer()
b.SetParallelism(*conc / runtime.GOMAXPROCS(0))
b.Run("strategy=jwt", func(b *testing.B) {
initialDBSpans := dbSpans(spans)
B := run(b, "jwt")
stop := profile(b)
defer stop()
var totalMS int64 = 0
b.RunParallel(func(p *testing.PB) {
defer func(t0 time.Time) {
atomic.AddInt64(&totalMS, int64(time.Since(t0).Milliseconds()))
}(time.Now())
for p.Next() {
B(b)
}
})
b.ReportMetric(0, "ns/op")
b.ReportMetric(float64(atomic.LoadInt64(&totalMS))/float64(b.N), "ms/op")
b.ReportMetric((float64(dbSpans(spans)-initialDBSpans))/float64(b.N), "queries/op")
b.ReportMetric(float64(b.N)/b.Elapsed().Seconds(), "ops/s")
})
b.Run("strategy=opaque", func(b *testing.B) {
initialDBSpans := dbSpans(spans)
B := run(b, "opaque")
stop := profile(b)
defer stop()
var totalMS int64 = 0
b.RunParallel(func(p *testing.PB) {
defer func(t0 time.Time) {
atomic.AddInt64(&totalMS, int64(time.Since(t0).Milliseconds()))
}(time.Now())
for p.Next() {
B(b)
}
})
b.ReportMetric(0, "ns/op")
b.ReportMetric(float64(atomic.LoadInt64(&totalMS))/float64(b.N), "ms/op")
b.ReportMetric((float64(dbSpans(spans)-initialDBSpans))/float64(b.N), "queries/op")
b.ReportMetric(float64(b.N)/b.Elapsed().Seconds(), "ops/s")
})
}
func profile(t testing.TB) (stop func()) {
t.Helper()
if *prof == "" {
return func() {} // noop
}
f, err := os.Create(*prof)
require.NoError(t, err)
require.NoError(t, pprof.StartCPUProfile(f))
return func() {
pprof.StopCPUProfile()
require.NoError(t, f.Close())
t.Log("Wrote profile to", f.Name())
}
} |
Go | hydra/oauth2/oauth2_auth_code_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2_test
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/go-jose/go-jose/v3"
"github.com/golang-jwt/jwt/v5"
"github.com/julienschmidt/httprouter"
"github.com/pborman/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
"github.com/ory/fosite"
hydra "github.com/ory/hydra-client-go/v2"
"github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/driver"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/flow"
"github.com/ory/hydra/v2/internal"
"github.com/ory/hydra/v2/internal/testhelpers"
hydraoauth2 "github.com/ory/hydra/v2/oauth2"
"github.com/ory/hydra/v2/x"
"github.com/ory/x/assertx"
"github.com/ory/x/contextx"
"github.com/ory/x/httprouterx"
"github.com/ory/x/httpx"
"github.com/ory/x/ioutilx"
"github.com/ory/x/josex"
"github.com/ory/x/pointerx"
"github.com/ory/x/requirex"
"github.com/ory/x/snapshotx"
"github.com/ory/x/stringsx"
)
func noopHandler(*testing.T) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
w.WriteHeader(http.StatusNotImplemented)
}
}
type clientCreator interface {
CreateClient(context.Context, *client.Client) error
}
// TestAuthCodeWithDefaultStrategy runs proper integration tests against in-memory and database connectors, specifically
// we test:
//
// - [x] If the flow - in general - works
// - [x] If `authenticatedAt` is properly managed across the lifecycle
// - [x] The value `authenticatedAt` should be an old time if no user interaction wrt login was required
// - [x] The value `authenticatedAt` should be a recent time if user interaction wrt login was required
//
// - [x] If `requestedAt` is properly managed across the lifecycle
// - [x] The value of `requestedAt` must be the initial request time, not some other time (e.g. when accepting login)
//
// - [x] If `id_token_hint` is handled properly
// - [x] What happens if `id_token_hint` does not match the value from the handled authentication request ("accept login")
func TestAuthCodeWithDefaultStrategy(t *testing.T) {
ctx := context.Background()
reg := internal.NewMockedRegistry(t, &contextx.Default{})
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, "opaque")
reg.Config().MustSet(ctx, config.KeyRefreshTokenHookURL, "")
publicTS, adminTS := testhelpers.NewOAuth2Server(ctx, t, reg)
publicClient := hydra.NewAPIClient(hydra.NewConfiguration())
publicClient.GetConfig().Servers = hydra.ServerConfigurations{{URL: publicTS.URL}}
adminClient := hydra.NewAPIClient(hydra.NewConfiguration())
adminClient.GetConfig().Servers = hydra.ServerConfigurations{{URL: adminTS.URL}}
getAuthorizeCode := func(t *testing.T, conf *oauth2.Config, c *http.Client, params ...oauth2.AuthCodeOption) (string, *http.Response) {
if c == nil {
c = testhelpers.NewEmptyJarClient(t)
}
state := uuid.New()
resp, err := c.Get(conf.AuthCodeURL(state, params...))
require.NoError(t, err)
defer resp.Body.Close()
q := resp.Request.URL.Query()
require.EqualValues(t, state, q.Get("state"))
return q.Get("code"), resp
}
acceptLoginHandler := func(t *testing.T, c *client.Client, subject string, checkRequestPayload func(request *hydra.OAuth2LoginRequest) *hydra.AcceptOAuth2LoginRequest) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
rr, _, err := adminClient.OAuth2Api.GetOAuth2LoginRequest(context.Background()).LoginChallenge(r.URL.Query().Get("login_challenge")).Execute()
require.NoError(t, err)
assert.EqualValues(t, c.GetID(), pointerx.Deref(rr.Client.ClientId))
assert.Empty(t, pointerx.Deref(rr.Client.ClientSecret))
assert.EqualValues(t, c.GrantTypes, rr.Client.GrantTypes)
assert.EqualValues(t, c.LogoURI, pointerx.Deref(rr.Client.LogoUri))
assert.EqualValues(t, c.RedirectURIs, rr.Client.RedirectUris)
assert.EqualValues(t, r.URL.Query().Get("login_challenge"), rr.Challenge)
assert.EqualValues(t, []string{"hydra", "offline", "openid"}, rr.RequestedScope)
assert.Contains(t, rr.RequestUrl, reg.Config().OAuth2AuthURL(ctx).String())
acceptBody := hydra.AcceptOAuth2LoginRequest{
Subject: subject,
Remember: pointerx.Ptr(!rr.Skip),
Acr: pointerx.Ptr("1"),
Amr: []string{"pwd"},
Context: map[string]interface{}{"context": "bar"},
}
if checkRequestPayload != nil {
if b := checkRequestPayload(rr); b != nil {
acceptBody = *b
}
}
v, _, err := adminClient.OAuth2Api.AcceptOAuth2LoginRequest(context.Background()).
LoginChallenge(r.URL.Query().Get("login_challenge")).
AcceptOAuth2LoginRequest(acceptBody).
Execute()
require.NoError(t, err)
require.NotEmpty(t, v.RedirectTo)
http.Redirect(w, r, v.RedirectTo, http.StatusFound)
}
}
acceptConsentHandler := func(t *testing.T, c *client.Client, subject string, checkRequestPayload func(*hydra.OAuth2ConsentRequest)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
rr, _, err := adminClient.OAuth2Api.GetOAuth2ConsentRequest(context.Background()).ConsentChallenge(r.URL.Query().Get("consent_challenge")).Execute()
require.NoError(t, err)
assert.EqualValues(t, c.GetID(), pointerx.Deref(rr.Client.ClientId))
assert.Empty(t, pointerx.Deref(rr.Client.ClientSecret))
assert.EqualValues(t, c.GrantTypes, rr.Client.GrantTypes)
assert.EqualValues(t, c.LogoURI, pointerx.Deref(rr.Client.LogoUri))
assert.EqualValues(t, c.RedirectURIs, rr.Client.RedirectUris)
assert.EqualValues(t, subject, pointerx.Deref(rr.Subject))
assert.EqualValues(t, []string{"hydra", "offline", "openid"}, rr.RequestedScope)
assert.EqualValues(t, r.URL.Query().Get("consent_challenge"), rr.Challenge)
assert.Contains(t, *rr.RequestUrl, reg.Config().OAuth2AuthURL(ctx).String())
if checkRequestPayload != nil {
checkRequestPayload(rr)
}
assert.Equal(t, map[string]interface{}{"context": "bar"}, rr.Context)
v, _, err := adminClient.OAuth2Api.AcceptOAuth2ConsentRequest(context.Background()).
ConsentChallenge(r.URL.Query().Get("consent_challenge")).
AcceptOAuth2ConsentRequest(hydra.AcceptOAuth2ConsentRequest{
GrantScope: []string{"hydra", "offline", "openid"}, Remember: pointerx.Ptr(true), RememberFor: pointerx.Ptr[int64](0),
GrantAccessTokenAudience: rr.RequestedAccessTokenAudience,
Session: &hydra.AcceptOAuth2ConsentRequestSession{
AccessToken: map[string]interface{}{"foo": "bar"},
IdToken: map[string]interface{}{"bar": "baz"},
},
}).
Execute()
require.NoError(t, err)
require.NotEmpty(t, v.RedirectTo)
http.Redirect(w, r, v.RedirectTo, http.StatusFound)
}
}
assertRefreshToken := func(t *testing.T, token *oauth2.Token, c *oauth2.Config, expectedExp time.Time) {
actualExp, err := strconv.ParseInt(testhelpers.IntrospectToken(t, c, token.RefreshToken, adminTS).Get("exp").String(), 10, 64)
require.NoError(t, err)
requirex.EqualTime(t, expectedExp, time.Unix(actualExp, 0), time.Second)
}
assertIDToken := func(t *testing.T, token *oauth2.Token, c *oauth2.Config, expectedSubject, expectedNonce string, expectedExp time.Time) gjson.Result {
idt, ok := token.Extra("id_token").(string)
require.True(t, ok)
assert.NotEmpty(t, idt)
body, err := x.DecodeSegment(strings.Split(idt, ".")[1])
require.NoError(t, err)
claims := gjson.ParseBytes(body)
assert.True(t, time.Now().After(time.Unix(claims.Get("iat").Int(), 0)), "%s", claims)
assert.True(t, time.Now().After(time.Unix(claims.Get("nbf").Int(), 0)), "%s", claims)
assert.True(t, time.Now().Before(time.Unix(claims.Get("exp").Int(), 0)), "%s", claims)
requirex.EqualTime(t, expectedExp, time.Unix(claims.Get("exp").Int(), 0), 2*time.Second)
assert.NotEmpty(t, claims.Get("jti").String(), "%s", claims)
assert.EqualValues(t, reg.Config().IssuerURL(ctx).String(), claims.Get("iss").String(), "%s", claims)
assert.NotEmpty(t, claims.Get("sid").String(), "%s", claims)
assert.Equal(t, "1", claims.Get("acr").String(), "%s", claims)
require.Len(t, claims.Get("amr").Array(), 1, "%s", claims)
assert.EqualValues(t, "pwd", claims.Get("amr").Array()[0].String(), "%s", claims)
require.Len(t, claims.Get("aud").Array(), 1, "%s", claims)
assert.EqualValues(t, c.ClientID, claims.Get("aud").Array()[0].String(), "%s", claims)
assert.EqualValues(t, expectedSubject, claims.Get("sub").String(), "%s", claims)
assert.EqualValues(t, expectedNonce, claims.Get("nonce").String(), "%s", claims)
assert.EqualValues(t, `baz`, claims.Get("bar").String(), "%s", claims)
return claims
}
introspectAccessToken := func(t *testing.T, conf *oauth2.Config, token *oauth2.Token, expectedSubject string) gjson.Result {
require.NotEmpty(t, token.AccessToken)
i := testhelpers.IntrospectToken(t, conf, token.AccessToken, adminTS)
assert.True(t, i.Get("active").Bool(), "%s", i)
assert.EqualValues(t, conf.ClientID, i.Get("client_id").String(), "%s", i)
assert.EqualValues(t, expectedSubject, i.Get("sub").String(), "%s", i)
assert.EqualValues(t, `bar`, i.Get("ext.foo").String(), "%s", i)
return i
}
assertJWTAccessToken := func(t *testing.T, strat string, conf *oauth2.Config, token *oauth2.Token, expectedSubject string, expectedExp time.Time, scopes string) gjson.Result {
require.NotEmpty(t, token.AccessToken)
parts := strings.Split(token.AccessToken, ".")
if strat != "jwt" {
require.Len(t, parts, 2)
return gjson.Parse("null")
}
require.Len(t, parts, 3)
body, err := x.DecodeSegment(parts[1])
require.NoError(t, err)
i := gjson.ParseBytes(body)
assert.NotEmpty(t, i.Get("jti").String())
assert.EqualValues(t, conf.ClientID, i.Get("client_id").String(), "%s", i)
assert.EqualValues(t, expectedSubject, i.Get("sub").String(), "%s", i)
assert.EqualValues(t, reg.Config().IssuerURL(ctx).String(), i.Get("iss").String(), "%s", i)
assert.True(t, time.Now().After(time.Unix(i.Get("iat").Int(), 0)), "%s", i)
assert.True(t, time.Now().After(time.Unix(i.Get("nbf").Int(), 0)), "%s", i)
assert.True(t, time.Now().Before(time.Unix(i.Get("exp").Int(), 0)), "%s", i)
requirex.EqualTime(t, expectedExp, time.Unix(i.Get("exp").Int(), 0), time.Second)
assert.EqualValues(t, `bar`, i.Get("ext.foo").String(), "%s", i)
assert.EqualValues(t, scopes, i.Get("scp").Raw, "%s", i)
return i
}
waitForRefreshTokenExpiry := func() {
time.Sleep(reg.Config().GetRefreshTokenLifespan(ctx) + time.Second)
}
t.Run("case=checks if request fails when audience does not match", func(t *testing.T) {
testhelpers.NewLoginConsentUI(t, reg.Config(), testhelpers.HTTPServerNoExpectedCallHandler(t), testhelpers.HTTPServerNoExpectedCallHandler(t))
_, conf := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
code, _ := getAuthorizeCode(t, conf, nil, oauth2.SetAuthURLParam("audience", "https://not-ory-api/"))
require.Empty(t, code)
})
subject := "aeneas-rekkas"
nonce := uuid.New()
t.Run("case=perform authorize code flow with ID token and refresh tokens", func(t *testing.T) {
run := func(t *testing.T, strategy string) {
c, conf := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, c, subject, nil),
acceptConsentHandler(t, c, subject, nil),
)
code, _ := getAuthorizeCode(t, conf, nil, oauth2.SetAuthURLParam("nonce", nonce))
require.NotEmpty(t, code)
token, err := conf.Exchange(context.Background(), code)
iat := time.Now()
require.NoError(t, err)
assert.Empty(t, token.Extra("c_nonce_draft_00"), "should not be set if not requested")
assert.Empty(t, token.Extra("c_nonce_expires_in_draft_00"), "should not be set if not requested")
introspectAccessToken(t, conf, token, subject)
assertJWTAccessToken(t, strategy, conf, token, subject, iat.Add(reg.Config().GetAccessTokenLifespan(ctx)), `["hydra","offline","openid"]`)
assertIDToken(t, token, conf, subject, nonce, iat.Add(reg.Config().GetIDTokenLifespan(ctx)))
assertRefreshToken(t, token, conf, iat.Add(reg.Config().GetRefreshTokenLifespan(ctx)))
t.Run("followup=successfully perform refresh token flow", func(t *testing.T) {
require.NotEmpty(t, token.RefreshToken)
token.Expiry = token.Expiry.Add(-time.Hour * 24)
iat = time.Now()
refreshedToken, err := conf.TokenSource(context.Background(), token).Token()
require.NoError(t, err)
require.NotEqual(t, token.AccessToken, refreshedToken.AccessToken)
require.NotEqual(t, token.RefreshToken, refreshedToken.RefreshToken)
require.NotEqual(t, token.Extra("id_token"), refreshedToken.Extra("id_token"))
introspectAccessToken(t, conf, refreshedToken, subject)
t.Run("followup=refreshed tokens contain valid tokens", func(t *testing.T) {
assertJWTAccessToken(t, strategy, conf, refreshedToken, subject, iat.Add(reg.Config().GetAccessTokenLifespan(ctx)), `["hydra","offline","openid"]`)
assertIDToken(t, refreshedToken, conf, subject, nonce, iat.Add(reg.Config().GetIDTokenLifespan(ctx)))
assertRefreshToken(t, refreshedToken, conf, iat.Add(reg.Config().GetRefreshTokenLifespan(ctx)))
})
t.Run("followup=original access token is no longer valid", func(t *testing.T) {
i := testhelpers.IntrospectToken(t, conf, token.AccessToken, adminTS)
assert.False(t, i.Get("active").Bool(), "%s", i)
})
t.Run("followup=original refresh token is no longer valid", func(t *testing.T) {
_, err := conf.TokenSource(context.Background(), token).Token()
assert.Error(t, err)
})
t.Run("followup=but fail subsequent refresh because expiry was reached", func(t *testing.T) {
waitForRefreshTokenExpiry()
// Force golang to refresh token
refreshedToken.Expiry = refreshedToken.Expiry.Add(-time.Hour * 24)
_, err := conf.TokenSource(context.Background(), refreshedToken).Token()
require.Error(t, err)
})
})
}
t.Run("strategy=jwt", func(t *testing.T) {
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, "jwt")
run(t, "jwt")
})
t.Run("strategy=opaque", func(t *testing.T) {
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, "opaque")
run(t, "opaque")
})
})
t.Run("case=perform authorize code flow with verifable credentials", func(t *testing.T) {
// Make sure we test against all crypto suites that we advertise.
cfg, _, err := publicClient.OidcApi.DiscoverOidcConfiguration(ctx).Execute()
require.NoError(t, err)
supportedCryptoSuites := cfg.CredentialsSupportedDraft00[0].CryptographicSuitesSupported
run := func(t *testing.T, strategy string) {
_, conf := newOAuth2Client(
t,
reg,
testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler),
withScope("openid userinfo_credential_draft_00"),
)
testhelpers.NewLoginConsentUI(t, reg.Config(),
func(w http.ResponseWriter, r *http.Request) {
acceptBody := hydra.AcceptOAuth2LoginRequest{
Subject: subject,
Acr: pointerx.Ptr("1"),
Amr: []string{"pwd"},
Context: map[string]interface{}{"context": "bar"},
}
v, _, err := adminClient.OAuth2Api.AcceptOAuth2LoginRequest(context.Background()).
LoginChallenge(r.URL.Query().Get("login_challenge")).
AcceptOAuth2LoginRequest(acceptBody).
Execute()
require.NoError(t, err)
require.NotEmpty(t, v.RedirectTo)
http.Redirect(w, r, v.RedirectTo, http.StatusFound)
},
func(w http.ResponseWriter, r *http.Request) {
rr, _, err := adminClient.OAuth2Api.GetOAuth2ConsentRequest(context.Background()).ConsentChallenge(r.URL.Query().Get("consent_challenge")).Execute()
require.NoError(t, err)
assert.Equal(t, map[string]interface{}{"context": "bar"}, rr.Context)
v, _, err := adminClient.OAuth2Api.AcceptOAuth2ConsentRequest(context.Background()).
ConsentChallenge(r.URL.Query().Get("consent_challenge")).
AcceptOAuth2ConsentRequest(hydra.AcceptOAuth2ConsentRequest{
GrantScope: []string{"openid", "userinfo_credential_draft_00"},
GrantAccessTokenAudience: rr.RequestedAccessTokenAudience,
Session: &hydra.AcceptOAuth2ConsentRequestSession{
AccessToken: map[string]interface{}{"foo": "bar"},
IdToken: map[string]interface{}{"bar": "baz"},
},
}).
Execute()
require.NoError(t, err)
require.NotEmpty(t, v.RedirectTo)
http.Redirect(w, r, v.RedirectTo, http.StatusFound)
},
)
code, _ := getAuthorizeCode(t, conf, nil,
oauth2.SetAuthURLParam("nonce", nonce),
oauth2.SetAuthURLParam("scope", "openid userinfo_credential_draft_00"),
)
require.NotEmpty(t, code)
token, err := conf.Exchange(context.Background(), code)
require.NoError(t, err)
iat := time.Now()
vcNonce := token.Extra("c_nonce_draft_00").(string)
assert.NotEmpty(t, vcNonce)
expiry := token.Extra("c_nonce_expires_in_draft_00")
assert.NotEmpty(t, expiry)
assert.NoError(t, reg.Persister().IsNonceValid(ctx, token.AccessToken, vcNonce))
t.Run("followup=successfully create a verifiable credential", func(t *testing.T) {
t.Parallel()
for _, alg := range supportedCryptoSuites {
alg := alg
t.Run(fmt.Sprintf("alg=%s", alg), func(t *testing.T) {
t.Parallel()
assertCreateVerifiableCredential(t, reg, vcNonce, token, jose.SignatureAlgorithm(alg))
})
}
})
t.Run("followup=get new nonce from priming request", func(t *testing.T) {
t.Parallel()
// Assert that we can fetch a verifiable credential with the nonce.
res, err := doPrimingRequest(t, reg, token, &hydraoauth2.CreateVerifiableCredentialRequestBody{
Format: "jwt_vc_json",
Types: []string{"VerifiableCredential", "UserInfoCredential"},
})
assert.NoError(t, err)
t.Run("followup=successfully create a verifiable credential from fresh nonce", func(t *testing.T) {
assertCreateVerifiableCredential(t, reg, res.Nonce, token, jose.ES256)
})
})
t.Run("followup=rejects proof signed by another key", func(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
name string
format string
proofType string
proof func() string
}{
{
name: "proof=mismatching keys",
proof: func() string {
// Create mismatching public and private keys.
pubKey, _, err := josex.NewSigningKey(jose.ES256, 0)
require.NoError(t, err)
_, privKey, err := josex.NewSigningKey(jose.ES256, 0)
require.NoError(t, err)
pubKeyJWK := &jose.JSONWebKey{Key: pubKey, Algorithm: string(jose.ES256)}
return createVCProofJWT(t, pubKeyJWK, privKey, vcNonce)
},
},
{
name: "proof=invalid format",
format: "invalid_format",
proof: func() string {
// Create mismatching public and private keys.
pubKey, privKey, err := josex.NewSigningKey(jose.ES256, 0)
require.NoError(t, err)
pubKeyJWK := &jose.JSONWebKey{Key: pubKey, Algorithm: string(jose.ES256)}
return createVCProofJWT(t, pubKeyJWK, privKey, vcNonce)
},
},
{
name: "proof=invalid type",
proofType: "invalid",
proof: func() string {
// Create mismatching public and private keys.
pubKey, privKey, err := josex.NewSigningKey(jose.ES256, 0)
require.NoError(t, err)
pubKeyJWK := &jose.JSONWebKey{Key: pubKey, Algorithm: string(jose.ES256)}
return createVCProofJWT(t, pubKeyJWK, privKey, vcNonce)
},
},
{
name: "proof=invalid nonce",
proof: func() string {
// Create mismatching public and private keys.
pubKey, privKey, err := josex.NewSigningKey(jose.ES256, 0)
require.NoError(t, err)
pubKeyJWK := &jose.JSONWebKey{Key: pubKey, Algorithm: string(jose.ES256)}
return createVCProofJWT(t, pubKeyJWK, privKey, "invalid nonce")
},
},
} {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
_, res := createVerifiableCredential(t, reg, token, &hydraoauth2.CreateVerifiableCredentialRequestBody{
Format: stringsx.Coalesce(tc.format, "jwt_vc_json"),
Types: []string{"VerifiableCredential", "UserInfoCredential"},
Proof: &hydraoauth2.VerifiableCredentialProof{
ProofType: stringsx.Coalesce(tc.proofType, "jwt"),
JWT: tc.proof(),
},
})
require.NoError(t, err)
require.NotNil(t, res)
assert.Equal(t, "invalid_request", res.Error())
})
}
})
t.Run("followup=access token and id token are valid", func(t *testing.T) {
assertJWTAccessToken(t, strategy, conf, token, subject, iat.Add(reg.Config().GetAccessTokenLifespan(ctx)), `["openid","userinfo_credential_draft_00"]`)
assertIDToken(t, token, conf, subject, nonce, iat.Add(reg.Config().GetIDTokenLifespan(ctx)))
})
}
t.Run("strategy=jwt", func(t *testing.T) {
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, "jwt")
run(t, "jwt")
})
t.Run("strategy=opaque", func(t *testing.T) {
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, "opaque")
run(t, "opaque")
})
})
t.Run("suite=invalid query params", func(t *testing.T) {
c, conf := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
otherClient, _ := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, c, subject, nil),
acceptConsentHandler(t, c, subject, nil),
)
withWrongClientAfterLogin := &http.Client{
Jar: testhelpers.NewEmptyCookieJar(t),
CheckRedirect: func(req *http.Request, _ []*http.Request) error {
if req.URL.Path != "/oauth2/auth" {
return nil
}
q := req.URL.Query()
if !q.Has("login_verifier") {
return nil
}
q.Set("client_id", otherClient.ID.String())
req.URL.RawQuery = q.Encode()
return nil
},
}
withWrongClientAfterConsent := &http.Client{
Jar: testhelpers.NewEmptyCookieJar(t),
CheckRedirect: func(req *http.Request, _ []*http.Request) error {
if req.URL.Path != "/oauth2/auth" {
return nil
}
q := req.URL.Query()
if !q.Has("consent_verifier") {
return nil
}
q.Set("client_id", otherClient.ID.String())
req.URL.RawQuery = q.Encode()
return nil
},
}
withWrongScopeAfterLogin := &http.Client{
Jar: testhelpers.NewEmptyCookieJar(t),
CheckRedirect: func(req *http.Request, _ []*http.Request) error {
if req.URL.Path != "/oauth2/auth" {
return nil
}
q := req.URL.Query()
if !q.Has("login_verifier") {
return nil
}
q.Set("scope", "invalid scope")
req.URL.RawQuery = q.Encode()
return nil
},
}
withWrongScopeAfterConsent := &http.Client{
Jar: testhelpers.NewEmptyCookieJar(t),
CheckRedirect: func(req *http.Request, _ []*http.Request) error {
if req.URL.Path != "/oauth2/auth" {
return nil
}
q := req.URL.Query()
if !q.Has("consent_verifier") {
return nil
}
q.Set("scope", "invalid scope")
req.URL.RawQuery = q.Encode()
return nil
},
}
for _, tc := range []struct {
name string
client *http.Client
expectedResponse string
}{{
name: "fails with wrong client ID after login",
client: withWrongClientAfterLogin,
expectedResponse: "access_denied",
}, {
name: "fails with wrong client ID after consent",
client: withWrongClientAfterConsent,
expectedResponse: "invalid_client",
}, {
name: "fails with wrong scopes after login",
client: withWrongScopeAfterLogin,
expectedResponse: "invalid_scope",
}, {
name: "fails with wrong scopes after consent",
client: withWrongScopeAfterConsent,
expectedResponse: "invalid_scope",
}} {
t.Run("case="+tc.name, func(t *testing.T) {
state := uuid.New()
resp, err := tc.client.Get(conf.AuthCodeURL(state))
require.NoError(t, err)
assert.Equal(t, tc.expectedResponse, resp.Request.URL.Query().Get("error"), "%s", resp.Request.URL.RawQuery)
resp.Body.Close()
})
}
})
t.Run("case=checks if request fails when subject is empty", func(t *testing.T) {
testhelpers.NewLoginConsentUI(t, reg.Config(), func(w http.ResponseWriter, r *http.Request) {
_, res, err := adminClient.OAuth2Api.AcceptOAuth2LoginRequest(ctx).
LoginChallenge(r.URL.Query().Get("login_challenge")).
AcceptOAuth2LoginRequest(hydra.AcceptOAuth2LoginRequest{Subject: "", Remember: pointerx.Ptr(true)}).Execute()
require.Error(t, err) // expects 400
body := string(ioutilx.MustReadAll(res.Body))
assert.Contains(t, body, "Field 'subject' must not be empty", "%s", body)
}, testhelpers.HTTPServerNoExpectedCallHandler(t))
_, conf := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
_, err := testhelpers.NewEmptyJarClient(t).Get(conf.AuthCodeURL(uuid.New()))
require.NoError(t, err)
})
t.Run("case=perform flow with audience", func(t *testing.T) {
expectAud := "https://api.ory.sh/"
c, conf := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, c, subject, func(r *hydra.OAuth2LoginRequest) *hydra.AcceptOAuth2LoginRequest {
assert.False(t, r.Skip)
assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience)
return nil
}),
acceptConsentHandler(t, c, subject, func(r *hydra.OAuth2ConsentRequest) {
assert.False(t, *r.Skip)
assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience)
}))
code, _ := getAuthorizeCode(t, conf, nil,
oauth2.SetAuthURLParam("audience", "https://api.ory.sh/"),
oauth2.SetAuthURLParam("nonce", nonce))
require.NotEmpty(t, code)
token, err := conf.Exchange(context.Background(), code)
require.NoError(t, err)
claims := introspectAccessToken(t, conf, token, subject)
aud := claims.Get("aud").Array()
require.Len(t, aud, 1)
assert.EqualValues(t, aud[0].String(), expectAud)
assertIDToken(t, token, conf, subject, nonce, time.Now().Add(reg.Config().GetIDTokenLifespan(ctx)))
})
t.Run("case=respects client token lifespan configuration", func(t *testing.T) {
run := func(t *testing.T, strategy string, c *client.Client, conf *oauth2.Config, expectedLifespans client.Lifespans) {
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, c, subject, nil),
acceptConsentHandler(t, c, subject, nil),
)
code, _ := getAuthorizeCode(t, conf, nil, oauth2.SetAuthURLParam("nonce", nonce))
require.NotEmpty(t, code)
token, err := conf.Exchange(context.Background(), code)
iat := time.Now()
require.NoError(t, err)
body := introspectAccessToken(t, conf, token, subject)
requirex.EqualTime(t, iat.Add(expectedLifespans.AuthorizationCodeGrantAccessTokenLifespan.Duration), time.Unix(body.Get("exp").Int(), 0), time.Second)
assertJWTAccessToken(t, strategy, conf, token, subject, iat.Add(expectedLifespans.AuthorizationCodeGrantAccessTokenLifespan.Duration), `["hydra","offline","openid"]`)
assertIDToken(t, token, conf, subject, nonce, iat.Add(expectedLifespans.AuthorizationCodeGrantIDTokenLifespan.Duration))
assertRefreshToken(t, token, conf, iat.Add(expectedLifespans.AuthorizationCodeGrantRefreshTokenLifespan.Duration))
t.Run("followup=successfully perform refresh token flow", func(t *testing.T) {
require.NotEmpty(t, token.RefreshToken)
token.Expiry = token.Expiry.Add(-time.Hour * 24)
refreshedToken, err := conf.TokenSource(context.Background(), token).Token()
iat = time.Now()
require.NoError(t, err)
assertRefreshToken(t, refreshedToken, conf, iat.Add(expectedLifespans.RefreshTokenGrantRefreshTokenLifespan.Duration))
assertJWTAccessToken(t, strategy, conf, refreshedToken, subject, iat.Add(expectedLifespans.RefreshTokenGrantAccessTokenLifespan.Duration), `["hydra","offline","openid"]`)
assertIDToken(t, refreshedToken, conf, subject, nonce, iat.Add(expectedLifespans.RefreshTokenGrantIDTokenLifespan.Duration))
require.NotEqual(t, token.AccessToken, refreshedToken.AccessToken)
require.NotEqual(t, token.RefreshToken, refreshedToken.RefreshToken)
require.NotEqual(t, token.Extra("id_token"), refreshedToken.Extra("id_token"))
body := introspectAccessToken(t, conf, refreshedToken, subject)
requirex.EqualTime(t, iat.Add(expectedLifespans.RefreshTokenGrantAccessTokenLifespan.Duration), time.Unix(body.Get("exp").Int(), 0), time.Second)
t.Run("followup=original access token is no longer valid", func(t *testing.T) {
i := testhelpers.IntrospectToken(t, conf, token.AccessToken, adminTS)
assert.False(t, i.Get("active").Bool(), "%s", i)
})
t.Run("followup=original refresh token is no longer valid", func(t *testing.T) {
_, err := conf.TokenSource(context.Background(), token).Token()
assert.Error(t, err)
})
})
}
t.Run("case=custom-lifespans-active-jwt", func(t *testing.T) {
c, conf := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
ls := testhelpers.TestLifespans
ls.AuthorizationCodeGrantAccessTokenLifespan = x.NullDuration{Valid: true, Duration: 6 * time.Second}
testhelpers.UpdateClientTokenLifespans(
t,
&oauth2.Config{ClientID: c.GetID(), ClientSecret: conf.ClientSecret},
c.GetID(),
ls, adminTS,
)
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, "jwt")
run(t, "jwt", c, conf, ls)
})
t.Run("case=custom-lifespans-active-opaque", func(t *testing.T) {
c, conf := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
ls := testhelpers.TestLifespans
ls.AuthorizationCodeGrantAccessTokenLifespan = x.NullDuration{Valid: true, Duration: 6 * time.Second}
testhelpers.UpdateClientTokenLifespans(
t,
&oauth2.Config{ClientID: c.GetID(), ClientSecret: conf.ClientSecret},
c.GetID(),
ls, adminTS,
)
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, "opaque")
run(t, "opaque", c, conf, ls)
})
t.Run("case=custom-lifespans-unset", func(t *testing.T) {
c, conf := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
testhelpers.UpdateClientTokenLifespans(t, &oauth2.Config{ClientID: c.GetID(), ClientSecret: conf.ClientSecret}, c.GetID(), testhelpers.TestLifespans, adminTS)
testhelpers.UpdateClientTokenLifespans(t, &oauth2.Config{ClientID: c.GetID(), ClientSecret: conf.ClientSecret}, c.GetID(), client.Lifespans{}, adminTS)
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, "opaque")
//goland:noinspection GoDeprecation
expectedLifespans := client.Lifespans{
AuthorizationCodeGrantAccessTokenLifespan: x.NullDuration{Valid: true, Duration: reg.Config().GetAccessTokenLifespan(ctx)},
AuthorizationCodeGrantIDTokenLifespan: x.NullDuration{Valid: true, Duration: reg.Config().GetIDTokenLifespan(ctx)},
AuthorizationCodeGrantRefreshTokenLifespan: x.NullDuration{Valid: true, Duration: reg.Config().GetRefreshTokenLifespan(ctx)},
ClientCredentialsGrantAccessTokenLifespan: x.NullDuration{Valid: true, Duration: reg.Config().GetAccessTokenLifespan(ctx)},
ImplicitGrantAccessTokenLifespan: x.NullDuration{Valid: true, Duration: reg.Config().GetAccessTokenLifespan(ctx)},
ImplicitGrantIDTokenLifespan: x.NullDuration{Valid: true, Duration: reg.Config().GetIDTokenLifespan(ctx)},
JwtBearerGrantAccessTokenLifespan: x.NullDuration{Valid: true, Duration: reg.Config().GetAccessTokenLifespan(ctx)},
PasswordGrantAccessTokenLifespan: x.NullDuration{Valid: true, Duration: reg.Config().GetAccessTokenLifespan(ctx)},
PasswordGrantRefreshTokenLifespan: x.NullDuration{Valid: true, Duration: reg.Config().GetRefreshTokenLifespan(ctx)},
RefreshTokenGrantIDTokenLifespan: x.NullDuration{Valid: true, Duration: reg.Config().GetIDTokenLifespan(ctx)},
RefreshTokenGrantAccessTokenLifespan: x.NullDuration{Valid: true, Duration: reg.Config().GetAccessTokenLifespan(ctx)},
RefreshTokenGrantRefreshTokenLifespan: x.NullDuration{Valid: true, Duration: reg.Config().GetRefreshTokenLifespan(ctx)},
}
run(t, "opaque", c, conf, expectedLifespans)
})
})
t.Run("case=use remember feature and prompt=none", func(t *testing.T) {
c, conf := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, c, subject, nil),
acceptConsentHandler(t, c, subject, nil),
)
oc := testhelpers.NewEmptyJarClient(t)
code, _ := getAuthorizeCode(t, conf, oc,
oauth2.SetAuthURLParam("nonce", nonce),
oauth2.SetAuthURLParam("prompt", "login consent"),
oauth2.SetAuthURLParam("max_age", "1"),
)
require.NotEmpty(t, code)
token, err := conf.Exchange(context.Background(), code)
require.NoError(t, err)
introspectAccessToken(t, conf, token, subject)
// Reset UI to check for skip values
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, c, subject, func(r *hydra.OAuth2LoginRequest) *hydra.AcceptOAuth2LoginRequest {
require.True(t, r.Skip)
require.EqualValues(t, subject, r.Subject)
return nil
}),
acceptConsentHandler(t, c, subject, func(r *hydra.OAuth2ConsentRequest) {
require.True(t, *r.Skip)
require.EqualValues(t, subject, *r.Subject)
}),
)
t.Run("followup=checks if authenticatedAt/requestedAt is properly forwarded across the lifecycle by checking if prompt=none works", func(t *testing.T) {
// In order to check if authenticatedAt/requestedAt works, we'll sleep first in order to ensure that authenticatedAt is in the past
// if handled correctly.
time.Sleep(time.Second + time.Nanosecond)
code, _ := getAuthorizeCode(t, conf, oc,
oauth2.SetAuthURLParam("nonce", nonce),
oauth2.SetAuthURLParam("prompt", "none"),
oauth2.SetAuthURLParam("max_age", "60"),
)
require.NotEmpty(t, code)
token, err := conf.Exchange(context.Background(), code)
require.NoError(t, err)
original := introspectAccessToken(t, conf, token, subject)
t.Run("followup=run the flow three more times", func(t *testing.T) {
for i := 0; i < 3; i++ {
t.Run(fmt.Sprintf("run=%d", i), func(t *testing.T) {
code, _ := getAuthorizeCode(t, conf, oc,
oauth2.SetAuthURLParam("nonce", nonce),
oauth2.SetAuthURLParam("prompt", "none"),
oauth2.SetAuthURLParam("max_age", "60"),
)
require.NotEmpty(t, code)
token, err := conf.Exchange(context.Background(), code)
require.NoError(t, err)
followup := introspectAccessToken(t, conf, token, subject)
assert.Equal(t, original.Get("auth_time").Int(), followup.Get("auth_time").Int())
})
}
})
t.Run("followup=fails when max age is reached and prompt is none", func(t *testing.T) {
code, _ := getAuthorizeCode(t, conf, oc,
oauth2.SetAuthURLParam("nonce", nonce),
oauth2.SetAuthURLParam("prompt", "none"),
oauth2.SetAuthURLParam("max_age", "1"),
)
require.Empty(t, code)
})
t.Run("followup=passes and resets skip when prompt=login", func(t *testing.T) {
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, c, subject, func(r *hydra.OAuth2LoginRequest) *hydra.AcceptOAuth2LoginRequest {
require.False(t, r.Skip)
require.Empty(t, r.Subject)
return nil
}),
acceptConsentHandler(t, c, subject, func(r *hydra.OAuth2ConsentRequest) {
require.True(t, *r.Skip)
require.EqualValues(t, subject, *r.Subject)
}),
)
code, _ := getAuthorizeCode(t, conf, oc,
oauth2.SetAuthURLParam("nonce", nonce),
oauth2.SetAuthURLParam("prompt", "login"),
oauth2.SetAuthURLParam("max_age", "1"),
)
require.NotEmpty(t, code)
token, err := conf.Exchange(context.Background(), code)
require.NoError(t, err)
introspectAccessToken(t, conf, token, subject)
assertIDToken(t, token, conf, subject, nonce, time.Now().Add(reg.Config().GetIDTokenLifespan(ctx)))
})
})
})
t.Run("case=should fail if prompt=none but no auth session given", func(t *testing.T) {
c, conf := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, c, subject, nil),
acceptConsentHandler(t, c, subject, nil),
)
oc := testhelpers.NewEmptyJarClient(t)
code, _ := getAuthorizeCode(t, conf, oc,
oauth2.SetAuthURLParam("prompt", "none"),
)
require.Empty(t, code)
})
t.Run("case=requires re-authentication when id_token_hint is set to a user 'patrik-neu' but the session is 'aeneas-rekkas' and then fails because the user id from the log in endpoint is 'aeneas-rekkas'", func(t *testing.T) {
c, conf := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, c, subject, func(r *hydra.OAuth2LoginRequest) *hydra.AcceptOAuth2LoginRequest {
require.False(t, r.Skip)
require.Empty(t, r.Subject)
return nil
}),
acceptConsentHandler(t, c, subject, nil),
)
oc := testhelpers.NewEmptyJarClient(t)
// Create login session for aeneas-rekkas
code, _ := getAuthorizeCode(t, conf, oc)
require.NotEmpty(t, code)
// Perform authentication for aeneas-rekkas which fails because id_token_hint is patrik-neu
code, _ = getAuthorizeCode(t, conf, oc,
oauth2.SetAuthURLParam("id_token_hint", testhelpers.NewIDToken(t, reg, "patrik-neu")),
)
require.Empty(t, code)
})
t.Run("case=should not cause issues if max_age is very low and consent takes a long time", func(t *testing.T) {
c, conf := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, c, subject, func(r *hydra.OAuth2LoginRequest) *hydra.AcceptOAuth2LoginRequest {
time.Sleep(time.Second * 2)
return nil
}),
acceptConsentHandler(t, c, subject, nil),
)
code, _ := getAuthorizeCode(t, conf, nil)
require.NotEmpty(t, code)
})
t.Run("case=ensure consistent claims returned for userinfo", func(t *testing.T) {
c, conf := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, c, subject, nil),
acceptConsentHandler(t, c, subject, nil),
)
code, _ := getAuthorizeCode(t, conf, nil)
require.NotEmpty(t, code)
token, err := conf.Exchange(context.Background(), code)
require.NoError(t, err)
idClaims := assertIDToken(t, token, conf, subject, "", time.Now().Add(reg.Config().GetIDTokenLifespan(ctx)))
time.Sleep(time.Second)
uiClaims := testhelpers.Userinfo(t, token, publicTS)
for _, f := range []string{
"sub",
"iss",
"aud",
"bar",
"auth_time",
} {
assert.NotEmpty(t, uiClaims.Get(f).Raw, "%s: %s", f, uiClaims)
assert.EqualValues(t, idClaims.Get(f).Raw, uiClaims.Get(f).Raw, "%s\nuserinfo: %s\nidtoken: %s", f, uiClaims, idClaims)
}
for _, f := range []string{
"at_hash",
"c_hash",
"nonce",
"sid",
"jti",
} {
assert.Empty(t, uiClaims.Get(f).Raw, "%s: %s", f, uiClaims)
}
})
t.Run("case=add ext claims from hook if configured", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, r.Header.Get("Content-Type"), "application/json; charset=UTF-8")
var hookReq hydraoauth2.TokenHookRequest
require.NoError(t, json.NewDecoder(r.Body).Decode(&hookReq))
require.NotEmpty(t, hookReq.Session)
require.Equal(t, hookReq.Session.Extra, map[string]interface{}{"foo": "bar"})
require.NotEmpty(t, hookReq.Request)
require.ElementsMatch(t, hookReq.Request.GrantedAudience, []string{})
require.Equal(t, hookReq.Request.Payload, map[string][]string{})
claims := map[string]interface{}{
"hooked": true,
}
hookResp := hydraoauth2.TokenHookResponse{
Session: flow.AcceptOAuth2ConsentRequestSession{
AccessToken: claims,
IDToken: claims,
},
}
w.WriteHeader(http.StatusOK)
require.NoError(t, json.NewEncoder(w).Encode(&hookResp))
}))
defer hs.Close()
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil)
expectAud := "https://api.ory.sh/"
c, conf := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, c, subject, func(r *hydra.OAuth2LoginRequest) *hydra.AcceptOAuth2LoginRequest {
assert.False(t, r.Skip)
assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience)
return nil
}),
acceptConsentHandler(t, c, subject, func(r *hydra.OAuth2ConsentRequest) {
assert.False(t, *r.Skip)
assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience)
}))
code, _ := getAuthorizeCode(t, conf, nil,
oauth2.SetAuthURLParam("audience", "https://api.ory.sh/"),
oauth2.SetAuthURLParam("nonce", nonce))
require.NotEmpty(t, code)
token, err := conf.Exchange(context.Background(), code)
require.NoError(t, err)
assertJWTAccessToken(t, strategy, conf, token, subject, time.Now().Add(reg.Config().GetAccessTokenLifespan(ctx)), `["hydra","offline","openid"]`)
// NOTE: using introspect to cover both jwt and opaque strategies
accessTokenClaims := introspectAccessToken(t, conf, token, subject)
require.True(t, accessTokenClaims.Get("ext.hooked").Bool())
idTokenClaims := assertIDToken(t, token, conf, subject, nonce, time.Now().Add(reg.Config().GetIDTokenLifespan(ctx)))
require.True(t, idTokenClaims.Get("hooked").Bool())
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("case=fail token exchange if hook fails", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer hs.Close()
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil)
expectAud := "https://api.ory.sh/"
c, conf := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, c, subject, func(r *hydra.OAuth2LoginRequest) *hydra.AcceptOAuth2LoginRequest {
assert.False(t, r.Skip)
assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience)
return nil
}),
acceptConsentHandler(t, c, subject, func(r *hydra.OAuth2ConsentRequest) {
assert.False(t, *r.Skip)
assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience)
}))
code, _ := getAuthorizeCode(t, conf, nil,
oauth2.SetAuthURLParam("audience", "https://api.ory.sh/"),
oauth2.SetAuthURLParam("nonce", nonce))
require.NotEmpty(t, code)
_, err := conf.Exchange(context.Background(), code)
require.Error(t, err)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("case=fail token exchange if hook denies the request", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
}))
defer hs.Close()
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil)
expectAud := "https://api.ory.sh/"
c, conf := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, c, subject, func(r *hydra.OAuth2LoginRequest) *hydra.AcceptOAuth2LoginRequest {
assert.False(t, r.Skip)
assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience)
return nil
}),
acceptConsentHandler(t, c, subject, func(r *hydra.OAuth2ConsentRequest) {
assert.False(t, *r.Skip)
assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience)
}))
code, _ := getAuthorizeCode(t, conf, nil,
oauth2.SetAuthURLParam("audience", "https://api.ory.sh/"),
oauth2.SetAuthURLParam("nonce", nonce))
require.NotEmpty(t, code)
_, err := conf.Exchange(context.Background(), code)
require.Error(t, err)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("case=fail token exchange if hook response is malformed", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer hs.Close()
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil)
expectAud := "https://api.ory.sh/"
c, conf := newOAuth2Client(t, reg, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, c, subject, func(r *hydra.OAuth2LoginRequest) *hydra.AcceptOAuth2LoginRequest {
assert.False(t, r.Skip)
assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience)
return nil
}),
acceptConsentHandler(t, c, subject, func(r *hydra.OAuth2ConsentRequest) {
assert.False(t, *r.Skip)
assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience)
}))
code, _ := getAuthorizeCode(t, conf, nil,
oauth2.SetAuthURLParam("audience", "https://api.ory.sh/"),
oauth2.SetAuthURLParam("nonce", nonce))
require.NotEmpty(t, code)
_, err := conf.Exchange(context.Background(), code)
require.Error(t, err)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
}
func assertCreateVerifiableCredential(t *testing.T, reg driver.Registry, nonce string, accessToken *oauth2.Token, alg jose.SignatureAlgorithm) {
// Build a proof from the nonce.
pubKey, privKey, err := josex.NewSigningKey(alg, 0)
require.NoError(t, err)
pubKeyJWK := &jose.JSONWebKey{Key: pubKey, Algorithm: string(alg)}
proofJWT := createVCProofJWT(t, pubKeyJWK, privKey, nonce)
// Assert that we can fetch a verifiable credential with the nonce.
verifiableCredential, _ := createVerifiableCredential(t, reg, accessToken, &hydraoauth2.CreateVerifiableCredentialRequestBody{
Format: "jwt_vc_json",
Types: []string{"VerifiableCredential", "UserInfoCredential"},
Proof: &hydraoauth2.VerifiableCredentialProof{
ProofType: "jwt",
JWT: proofJWT,
},
})
require.NoError(t, err)
assertVerifiableCredentialContainsPublicKey(t, reg, verifiableCredential, pubKeyJWK)
}
func assertVerifiableCredentialContainsPublicKey(t *testing.T, reg driver.Registry, vc *hydraoauth2.VerifiableCredentialResponse, pubKeyJWK *jose.JSONWebKey) {
ctx := context.Background()
token, err := jwt.Parse(vc.Credential, func(token *jwt.Token) (interface{}, error) {
kid, found := token.Header["kid"]
if !found {
return nil, errors.New("missing kid header")
}
openIDKey, err := reg.OpenIDJWTStrategy().GetPublicKeyID(ctx)
if err != nil {
return nil, err
}
if kid != openIDKey {
return nil, errors.New("invalid kid header")
}
return x.Must(reg.OpenIDJWTStrategy().GetPublicKey(ctx)).Key, nil
})
require.NoError(t, err)
pubKeyRaw, err := pubKeyJWK.MarshalJSON()
require.NoError(t, err)
expectedID := fmt.Sprintf("did:jwk:%s", base64.RawURLEncoding.EncodeToString(pubKeyRaw))
require.Equal(t, expectedID, token.Claims.(jwt.MapClaims)["vc"].(map[string]any)["credentialSubject"].(map[string]any)["id"])
}
func createVerifiableCredential(
t *testing.T,
reg driver.Registry,
token *oauth2.Token,
createVerifiableCredentialReq *hydraoauth2.CreateVerifiableCredentialRequestBody,
) (vcRes *hydraoauth2.VerifiableCredentialResponse, vcErr *fosite.RFC6749Error) {
var (
ctx = context.Background()
body bytes.Buffer
)
require.NoError(t, json.NewEncoder(&body).Encode(createVerifiableCredentialReq))
req := httpx.MustNewRequest("POST", reg.Config().CredentialsEndpointURL(ctx).String(), &body, "application/json")
req.Header.Set("Authorization", "Bearer "+token.AccessToken)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
var errRes fosite.RFC6749Error
require.NoError(t, json.NewDecoder(res.Body).Decode(&errRes))
return nil, &errRes
}
require.Equal(t, http.StatusOK, res.StatusCode)
var vc hydraoauth2.VerifiableCredentialResponse
require.NoError(t, json.NewDecoder(res.Body).Decode(&vc))
return &vc, vcErr
}
func doPrimingRequest(
t *testing.T,
reg driver.Registry,
token *oauth2.Token,
createVerifiableCredentialReq *hydraoauth2.CreateVerifiableCredentialRequestBody,
) (*hydraoauth2.VerifiableCredentialPrimingResponse, error) {
var (
ctx = context.Background()
body bytes.Buffer
)
require.NoError(t, json.NewEncoder(&body).Encode(createVerifiableCredentialReq))
req := httpx.MustNewRequest("POST", reg.Config().CredentialsEndpointURL(ctx).String(), &body, "application/json")
req.Header.Set("Authorization", "Bearer "+token.AccessToken)
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
require.Equal(t, http.StatusBadRequest, res.StatusCode)
var vc hydraoauth2.VerifiableCredentialPrimingResponse
require.NoError(t, json.NewDecoder(res.Body).Decode(&vc))
return &vc, nil
}
func createVCProofJWT(t *testing.T, pubKey *jose.JSONWebKey, privKey any, nonce string) string {
proofToken := jwt.NewWithClaims(jwt.GetSigningMethod(string(pubKey.Algorithm)), jwt.MapClaims{"nonce": nonce})
proofToken.Header["jwk"] = pubKey
proofJWT, err := proofToken.SignedString(privKey)
require.NoError(t, err)
return proofJWT
}
// TestAuthCodeWithMockStrategy runs the authorization_code flow against various ConsentStrategy scenarios.
// For that purpose, the consent strategy is mocked so all scenarios can be applied properly. This test suite checks:
//
// - [x] should pass request if strategy passes
// - [x] should fail because prompt=none and max_age > auth_time
// - [x] should pass because prompt=none and max_age < auth_time
// - [x] should fail because prompt=none but auth_time suggests recent authentication
// - [x] should fail because consent strategy fails
// - [x] should pass with prompt=login when authentication time is recent
// - [x] should fail with prompt=login when authentication time is in the past
func TestAuthCodeWithMockStrategy(t *testing.T) {
ctx := context.Background()
for _, strat := range []struct{ d string }{{d: "opaque"}, {d: "jwt"}} {
t.Run("strategy="+strat.d, func(t *testing.T) {
conf := internal.NewConfigurationWithDefaults()
conf.MustSet(ctx, config.KeyAccessTokenLifespan, time.Second*2)
conf.MustSet(ctx, config.KeyScopeStrategy, "DEPRECATED_HIERARCHICAL_SCOPE_STRATEGY")
conf.MustSet(ctx, config.KeyAccessTokenStrategy, strat.d)
reg := internal.NewRegistryMemory(t, conf, &contextx.Default{})
internal.MustEnsureRegistryKeys(ctx, reg, x.OpenIDConnectKeyName)
internal.MustEnsureRegistryKeys(ctx, reg, x.OAuth2JWTKeyName)
consentStrategy := &consentMock{}
router := x.NewRouterPublic()
ts := httptest.NewServer(router)
defer ts.Close()
reg.WithConsentStrategy(consentStrategy)
handler := reg.OAuth2Handler()
handler.SetRoutes(httprouterx.NewRouterAdminWithPrefixAndRouter(router.Router, "/admin", conf.AdminURL), router, func(h http.Handler) http.Handler {
return h
})
var callbackHandler *httprouter.Handle
router.GET("/callback", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
(*callbackHandler)(w, r, ps)
})
var mutex sync.Mutex
require.NoError(t, reg.ClientManager().CreateClient(context.TODO(), &client.Client{
LegacyClientID: "app-client",
Secret: "secret",
RedirectURIs: []string{ts.URL + "/callback"},
ResponseTypes: []string{"id_token", "code", "token"},
GrantTypes: []string{"implicit", "refresh_token", "authorization_code", "password", "client_credentials"},
Scope: "hydra.* offline openid",
}))
oauthConfig := &oauth2.Config{
ClientID: "app-client",
ClientSecret: "secret",
Endpoint: oauth2.Endpoint{
AuthURL: ts.URL + "/oauth2/auth",
TokenURL: ts.URL + "/oauth2/token",
},
RedirectURL: ts.URL + "/callback",
Scopes: []string{"hydra.*", "offline", "openid"},
}
var code string
for k, tc := range []struct {
cj http.CookieJar
d string
cb func(t *testing.T) httprouter.Handle
authURL string
shouldPassConsentStrategy bool
expectOAuthAuthError bool
expectOAuthTokenError bool
checkExpiry bool
authTime time.Time
requestTime time.Time
assertAccessToken func(*testing.T, string)
}{
{
d: "should pass request if strategy passes",
authURL: oauthConfig.AuthCodeURL("some-foo-state"),
shouldPassConsentStrategy: true,
checkExpiry: true,
cb: func(t *testing.T) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
code = r.URL.Query().Get("code")
require.NotEmpty(t, code)
_, _ = w.Write([]byte(r.URL.Query().Get("code")))
}
},
assertAccessToken: func(t *testing.T, token string) {
if strat.d != "jwt" {
return
}
body, err := x.DecodeSegment(strings.Split(token, ".")[1])
require.NoError(t, err)
data := map[string]interface{}{}
require.NoError(t, json.Unmarshal(body, &data))
assert.EqualValues(t, "app-client", data["client_id"])
assert.EqualValues(t, "foo", data["sub"])
assert.NotEmpty(t, data["iss"])
assert.NotEmpty(t, data["jti"])
assert.NotEmpty(t, data["exp"])
assert.NotEmpty(t, data["iat"])
assert.NotEmpty(t, data["nbf"])
assert.EqualValues(t, data["nbf"], data["iat"])
assert.EqualValues(t, []interface{}{"offline", "openid", "hydra.*"}, data["scp"])
},
},
{
d: "should fail because prompt=none and max_age > auth_time",
authURL: oauthConfig.AuthCodeURL("some-foo-state") + "&prompt=none&max_age=1",
authTime: time.Now().UTC().Add(-time.Minute),
requestTime: time.Now().UTC(),
shouldPassConsentStrategy: true,
cb: func(t *testing.T) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
code = r.URL.Query().Get("code")
err := r.URL.Query().Get("error")
require.Empty(t, code)
require.EqualValues(t, fosite.ErrLoginRequired.Error(), err)
}
},
expectOAuthAuthError: true,
},
{
d: "should pass because prompt=none and max_age is less than auth_time",
authURL: oauthConfig.AuthCodeURL("some-foo-state") + "&prompt=none&max_age=3600",
authTime: time.Now().UTC().Add(-time.Minute),
requestTime: time.Now().UTC(),
shouldPassConsentStrategy: true,
cb: func(t *testing.T) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
code = r.URL.Query().Get("code")
require.NotEmpty(t, code)
_, _ = w.Write([]byte(r.URL.Query().Get("code")))
}
},
},
{
d: "should fail because prompt=none but auth_time suggests recent authentication",
authURL: oauthConfig.AuthCodeURL("some-foo-state") + "&prompt=none",
authTime: time.Now().UTC().Add(-time.Minute),
requestTime: time.Now().UTC().Add(-time.Hour),
shouldPassConsentStrategy: true,
cb: func(t *testing.T) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
code = r.URL.Query().Get("code")
err := r.URL.Query().Get("error")
require.Empty(t, code)
require.EqualValues(t, fosite.ErrLoginRequired.Error(), err)
}
},
expectOAuthAuthError: true,
},
{
d: "should fail because consent strategy fails",
authURL: oauthConfig.AuthCodeURL("some-foo-state"),
expectOAuthAuthError: true,
shouldPassConsentStrategy: false,
cb: func(t *testing.T) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
require.Empty(t, r.URL.Query().Get("code"))
assert.Equal(t, fosite.ErrRequestForbidden.Error(), r.URL.Query().Get("error"))
}
},
},
{
d: "should pass with prompt=login when authentication time is recent",
authURL: oauthConfig.AuthCodeURL("some-foo-state") + "&prompt=login",
authTime: time.Now().UTC().Add(-time.Second),
requestTime: time.Now().UTC().Add(-time.Minute),
shouldPassConsentStrategy: true,
cb: func(t *testing.T) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
code = r.URL.Query().Get("code")
require.NotEmpty(t, code)
_, _ = w.Write([]byte(r.URL.Query().Get("code")))
}
},
},
{
d: "should fail with prompt=login when authentication time is in the past",
authURL: oauthConfig.AuthCodeURL("some-foo-state") + "&prompt=login",
authTime: time.Now().UTC().Add(-time.Minute),
requestTime: time.Now().UTC(),
expectOAuthAuthError: true,
shouldPassConsentStrategy: true,
cb: func(t *testing.T) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
code = r.URL.Query().Get("code")
require.Empty(t, code)
assert.Equal(t, fosite.ErrLoginRequired.Error(), r.URL.Query().Get("error"))
}
},
},
} {
t.Run(fmt.Sprintf("case=%d/description=%s", k, tc.d), func(t *testing.T) {
mutex.Lock()
defer mutex.Unlock()
if tc.cb == nil {
tc.cb = noopHandler
}
consentStrategy.deny = !tc.shouldPassConsentStrategy
consentStrategy.authTime = tc.authTime
consentStrategy.requestTime = tc.requestTime
cb := tc.cb(t)
callbackHandler = &cb
req, err := http.NewRequest("GET", tc.authURL, nil)
require.NoError(t, err)
if tc.cj == nil {
tc.cj = testhelpers.NewEmptyCookieJar(t)
}
resp, err := (&http.Client{Jar: tc.cj}).Do(req)
require.NoError(t, err, tc.authURL, ts.URL)
defer resp.Body.Close()
if tc.expectOAuthAuthError {
require.Empty(t, code)
return
}
require.NotEmpty(t, code)
token, err := oauthConfig.Exchange(context.TODO(), code)
if tc.expectOAuthTokenError {
require.Error(t, err)
return
}
require.NoError(t, err, code)
if tc.assertAccessToken != nil {
tc.assertAccessToken(t, token.AccessToken)
}
t.Run("case=userinfo", func(t *testing.T) {
var makeRequest = func(req *http.Request) *http.Response {
resp, err = http.DefaultClient.Do(req)
require.NoError(t, err)
return resp
}
var testSuccess = func(response *http.Response) {
defer resp.Body.Close()
require.Equal(t, http.StatusOK, resp.StatusCode)
var claims map[string]interface{}
require.NoError(t, json.NewDecoder(resp.Body).Decode(&claims))
assert.Equal(t, "foo", claims["sub"])
}
req, err = http.NewRequest("GET", ts.URL+"/userinfo", nil)
req.Header.Add("Authorization", "bearer "+token.AccessToken)
testSuccess(makeRequest(req))
req, err = http.NewRequest("POST", ts.URL+"/userinfo", nil)
req.Header.Add("Authorization", "bearer "+token.AccessToken)
testSuccess(makeRequest(req))
req, err = http.NewRequest("POST", ts.URL+"/userinfo", bytes.NewBuffer([]byte("access_token="+token.AccessToken)))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
testSuccess(makeRequest(req))
req, err = http.NewRequest("GET", ts.URL+"/userinfo", nil)
req.Header.Add("Authorization", "bearer asdfg")
resp := makeRequest(req)
require.Equal(t, http.StatusUnauthorized, resp.StatusCode)
})
res, err := testRefresh(t, token, ts.URL, tc.checkExpiry)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
var refreshedToken oauth2.Token
require.NoError(t, json.Unmarshal(body, &refreshedToken))
if tc.assertAccessToken != nil {
tc.assertAccessToken(t, refreshedToken.AccessToken)
}
t.Run("the tokens should be different", func(t *testing.T) {
if strat.d != "jwt" {
t.Skip()
}
body, err := x.DecodeSegment(strings.Split(token.AccessToken, ".")[1])
require.NoError(t, err)
origPayload := map[string]interface{}{}
require.NoError(t, json.Unmarshal(body, &origPayload))
body, err = x.DecodeSegment(strings.Split(refreshedToken.AccessToken, ".")[1])
require.NoError(t, err)
refreshedPayload := map[string]interface{}{}
require.NoError(t, json.Unmarshal(body, &refreshedPayload))
if tc.checkExpiry {
assert.NotEqual(t, refreshedPayload["exp"], origPayload["exp"])
assert.NotEqual(t, refreshedPayload["iat"], origPayload["iat"])
assert.NotEqual(t, refreshedPayload["nbf"], origPayload["nbf"])
}
assert.NotEqual(t, refreshedPayload["jti"], origPayload["jti"])
assert.Equal(t, refreshedPayload["client_id"], origPayload["client_id"])
})
require.NotEqual(t, token.AccessToken, refreshedToken.AccessToken)
t.Run("old token should no longer be usable", func(t *testing.T) {
req, err := http.NewRequest("GET", ts.URL+"/userinfo", nil)
require.NoError(t, err)
req.Header.Add("Authorization", "bearer "+token.AccessToken)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.EqualValues(t, http.StatusUnauthorized, res.StatusCode)
})
t.Run("refreshing new refresh token should work", func(t *testing.T) {
res, err := testRefresh(t, &refreshedToken, ts.URL, false)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(body, &refreshedToken))
})
t.Run("should call refresh token hook if configured", func(t *testing.T) {
run := func(hookType string) func(t *testing.T) {
return func(t *testing.T) {
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, r.Header.Get("Content-Type"), "application/json; charset=UTF-8")
expectedGrantedScopes := []string{"openid", "offline", "hydra.*"}
expectedSubject := "foo"
exceptKeys := []string{
"session.kid",
"session.id_token.expires_at",
"session.id_token.headers.extra.kid",
"session.id_token.id_token_claims.iat",
"session.id_token.id_token_claims.exp",
"session.id_token.id_token_claims.rat",
"session.id_token.id_token_claims.auth_time",
}
if hookType == "legacy" {
var hookReq hydraoauth2.RefreshTokenHookRequest
require.NoError(t, json.NewDecoder(r.Body).Decode(&hookReq))
require.Equal(t, hookReq.Subject, expectedSubject)
require.ElementsMatch(t, hookReq.GrantedScopes, expectedGrantedScopes)
require.ElementsMatch(t, hookReq.GrantedAudience, []string{})
require.Equal(t, hookReq.ClientID, oauthConfig.ClientID)
require.NotEmpty(t, hookReq.Session)
require.Equal(t, hookReq.Session.Subject, expectedSubject)
require.Equal(t, hookReq.Session.ClientID, oauthConfig.ClientID)
require.NotEmpty(t, hookReq.Requester)
require.Equal(t, hookReq.Requester.ClientID, oauthConfig.ClientID)
require.ElementsMatch(t, hookReq.Requester.GrantedScopes, expectedGrantedScopes)
snapshotx.SnapshotT(t, hookReq, snapshotx.ExceptPaths(exceptKeys...))
} else {
var hookReq hydraoauth2.TokenHookRequest
require.NoError(t, json.NewDecoder(r.Body).Decode(&hookReq))
require.NotEmpty(t, hookReq.Session)
require.Equal(t, hookReq.Session.Subject, expectedSubject)
require.Equal(t, hookReq.Session.ClientID, oauthConfig.ClientID)
require.NotEmpty(t, hookReq.Request)
require.Equal(t, hookReq.Request.ClientID, oauthConfig.ClientID)
require.ElementsMatch(t, hookReq.Request.GrantedScopes, expectedGrantedScopes)
require.ElementsMatch(t, hookReq.Request.GrantedAudience, []string{})
require.Equal(t, hookReq.Request.Payload, map[string][]string{})
snapshotx.SnapshotT(t, hookReq, snapshotx.ExceptPaths(exceptKeys...))
}
claims := map[string]interface{}{
"hooked": hookType,
}
hookResp := hydraoauth2.TokenHookResponse{
Session: flow.AcceptOAuth2ConsentRequestSession{
AccessToken: claims,
IDToken: claims,
},
}
w.WriteHeader(http.StatusOK)
require.NoError(t, json.NewEncoder(w).Encode(&hookResp))
}))
defer hs.Close()
if hookType == "legacy" {
conf.MustSet(ctx, config.KeyRefreshTokenHookURL, hs.URL)
defer conf.MustSet(ctx, config.KeyRefreshTokenHookURL, nil)
} else {
conf.MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer conf.MustSet(ctx, config.KeyTokenHookURL, nil)
}
res, err := testRefresh(t, &refreshedToken, ts.URL, false)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(body, &refreshedToken))
accessTokenClaims := testhelpers.IntrospectToken(t, oauthConfig, refreshedToken.AccessToken, ts)
require.Equal(t, accessTokenClaims.Get("ext.hooked").String(), hookType)
idTokenBody, err := x.DecodeSegment(
strings.Split(
gjson.GetBytes(body, "id_token").String(),
".",
)[1],
)
require.NoError(t, err)
require.Equal(t, gjson.GetBytes(idTokenBody, "hooked").String(), hookType)
}
}
t.Run("hook=legacy", run("legacy"))
t.Run("hook=new", run("new"))
})
t.Run("should not override session data if token refresh hook returns no content", func(t *testing.T) {
run := func(hookType string) func(t *testing.T) {
return func(t *testing.T) {
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}))
defer hs.Close()
if hookType == "legacy" {
conf.MustSet(ctx, config.KeyRefreshTokenHookURL, hs.URL)
defer conf.MustSet(ctx, config.KeyRefreshTokenHookURL, nil)
} else {
conf.MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer conf.MustSet(ctx, config.KeyTokenHookURL, nil)
}
origAccessTokenClaims := testhelpers.IntrospectToken(t, oauthConfig, refreshedToken.AccessToken, ts)
res, err := testRefresh(t, &refreshedToken, ts.URL, false)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
body, err = io.ReadAll(res.Body)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(body, &refreshedToken))
refreshedAccessTokenClaims := testhelpers.IntrospectToken(t, oauthConfig, refreshedToken.AccessToken, ts)
assertx.EqualAsJSONExcept(t, json.RawMessage(origAccessTokenClaims.Raw), json.RawMessage(refreshedAccessTokenClaims.Raw), []string{"exp", "iat", "nbf"})
}
}
t.Run("hook=legacy", run("legacy"))
t.Run("hook=new", run("new"))
})
t.Run("should fail token refresh with `server_error` if refresh hook fails", func(t *testing.T) {
run := func(hookType string) func(t *testing.T) {
return func(t *testing.T) {
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer hs.Close()
if hookType == "legacy" {
conf.MustSet(ctx, config.KeyRefreshTokenHookURL, hs.URL)
defer conf.MustSet(ctx, config.KeyRefreshTokenHookURL, nil)
} else {
conf.MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer conf.MustSet(ctx, config.KeyTokenHookURL, nil)
}
res, err := testRefresh(t, &refreshedToken, ts.URL, false)
require.NoError(t, err)
assert.Equal(t, http.StatusInternalServerError, res.StatusCode)
var errBody fosite.RFC6749ErrorJson
require.NoError(t, json.NewDecoder(res.Body).Decode(&errBody))
require.Equal(t, fosite.ErrServerError.Error(), errBody.Name)
require.Equal(t, "An error occurred while executing the token hook.", errBody.Description)
}
}
t.Run("hook=legacy", run("legacy"))
t.Run("hook=new", run("new"))
})
t.Run("should fail token refresh with `access_denied` if legacy refresh hook denied the request", func(t *testing.T) {
run := func(hookType string) func(t *testing.T) {
return func(t *testing.T) {
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
}))
defer hs.Close()
if hookType == "legacy" {
conf.MustSet(ctx, config.KeyRefreshTokenHookURL, hs.URL)
defer conf.MustSet(ctx, config.KeyRefreshTokenHookURL, nil)
} else {
conf.MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer conf.MustSet(ctx, config.KeyTokenHookURL, nil)
}
res, err := testRefresh(t, &refreshedToken, ts.URL, false)
require.NoError(t, err)
assert.Equal(t, http.StatusForbidden, res.StatusCode)
var errBody fosite.RFC6749ErrorJson
require.NoError(t, json.NewDecoder(res.Body).Decode(&errBody))
require.Equal(t, fosite.ErrAccessDenied.Error(), errBody.Name)
require.Equal(t, "The token hook target responded with an error. Make sure that the request you are making is valid. Maybe the credential or request parameters you are using are limited in scope or otherwise restricted.", errBody.Description)
}
}
t.Run("hook=legacy", run("legacy"))
t.Run("hook=new", run("new"))
})
t.Run("should fail token refresh with `server_error` if refresh hook response is malformed", func(t *testing.T) {
run := func(hookType string) func(t *testing.T) {
return func(t *testing.T) {
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer hs.Close()
if hookType == "legacy" {
conf.MustSet(ctx, config.KeyRefreshTokenHookURL, hs.URL)
defer conf.MustSet(ctx, config.KeyRefreshTokenHookURL, nil)
} else {
conf.MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer conf.MustSet(ctx, config.KeyTokenHookURL, nil)
}
res, err := testRefresh(t, &refreshedToken, ts.URL, false)
require.NoError(t, err)
assert.Equal(t, http.StatusInternalServerError, res.StatusCode)
var errBody fosite.RFC6749ErrorJson
require.NoError(t, json.NewDecoder(res.Body).Decode(&errBody))
require.Equal(t, fosite.ErrServerError.Error(), errBody.Name)
require.Equal(t, "The token hook target responded with an error.", errBody.Description)
}
}
t.Run("hook=legacy", run("legacy"))
t.Run("hook=new", run("new"))
})
t.Run("refreshing old token should no longer work", func(t *testing.T) {
res, err := testRefresh(t, token, ts.URL, false)
require.NoError(t, err)
assert.Equal(t, http.StatusUnauthorized, res.StatusCode)
})
t.Run("attempt to refresh old token should revoke new token", func(t *testing.T) {
res, err := testRefresh(t, &refreshedToken, ts.URL, false)
require.NoError(t, err)
assert.Equal(t, http.StatusUnauthorized, res.StatusCode)
})
t.Run("duplicate code exchange fails", func(t *testing.T) {
token, err := oauthConfig.Exchange(context.TODO(), code)
require.Error(t, err)
require.Nil(t, token)
})
code = ""
})
}
})
}
}
func testRefresh(t *testing.T, token *oauth2.Token, u string, sleep bool) (*http.Response, error) {
if sleep {
time.Sleep(time.Millisecond * 1001)
}
oauthClientConfig := &clientcredentials.Config{
ClientID: "app-client",
ClientSecret: "secret",
TokenURL: u + "/oauth2/token",
Scopes: []string{"foobar"},
}
req, err := http.NewRequest("POST", oauthClientConfig.TokenURL, strings.NewReader(url.Values{
"grant_type": []string{"refresh_token"},
"refresh_token": []string{token.RefreshToken},
}.Encode()))
require.NoError(t, err)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.SetBasicAuth(oauthClientConfig.ClientID, oauthClientConfig.ClientSecret)
return http.DefaultClient.Do(req)
}
func withScope(scope string) func(*client.Client) {
return func(c *client.Client) {
c.Scope = scope
}
}
func newOAuth2Client(
t *testing.T,
reg interface {
config.Provider
client.Registry
},
callbackURL string,
opts ...func(*client.Client),
) (*client.Client, *oauth2.Config) {
ctx := context.Background()
secret := uuid.New()
c := &client.Client{
Secret: secret,
RedirectURIs: []string{callbackURL},
ResponseTypes: []string{"id_token", "code", "token"},
GrantTypes: []string{
"implicit",
"refresh_token",
"authorization_code",
"password",
"client_credentials",
},
Scope: "hydra offline openid",
Audience: []string{"https://api.ory.sh/"},
}
// apply options
for _, o := range opts {
o(c)
}
require.NoError(t, reg.ClientManager().CreateClient(ctx, c))
return c, &oauth2.Config{
ClientID: c.GetID(),
ClientSecret: secret,
Endpoint: oauth2.Endpoint{
AuthURL: reg.Config().OAuth2AuthURL(ctx).String(),
TokenURL: reg.Config().OAuth2TokenURL(ctx).String(),
AuthStyle: oauth2.AuthStyleInHeader,
},
Scopes: strings.Split(c.Scope, " "),
}
} |
Go | hydra/oauth2/oauth2_client_credentials_bench_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2_test
import (
"context"
"encoding/json"
"net/url"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
"go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
goauth2 "golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
hc "github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/internal"
"github.com/ory/hydra/v2/internal/testhelpers"
"github.com/ory/hydra/v2/x"
"github.com/ory/x/contextx"
"github.com/ory/x/requirex"
)
func BenchmarkClientCredentials(b *testing.B) {
ctx := context.Background()
spans := tracetest.NewSpanRecorder()
tracer := trace.NewTracerProvider(trace.WithSpanProcessor(spans)).Tracer("")
dsn := "postgres://postgres:[email protected]:3445/postgres?sslmode=disable"
reg := internal.NewRegistrySQLFromURL(b, dsn, true, new(contextx.Default)).WithTracer(tracer)
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, "opaque")
public, admin := testhelpers.NewOAuth2Server(ctx, b, reg)
var newCustomClient = func(b *testing.B, c *hc.Client) (*hc.Client, clientcredentials.Config) {
unhashedSecret := c.Secret
require.NoError(b, reg.ClientManager().CreateClient(ctx, c))
return c, clientcredentials.Config{
ClientID: c.GetID(),
ClientSecret: unhashedSecret,
TokenURL: reg.Config().OAuth2TokenURL(ctx).String(),
Scopes: strings.Split(c.Scope, " "),
EndpointParams: url.Values{"audience": c.Audience},
}
}
var newClient = func(b *testing.B) (*hc.Client, clientcredentials.Config) {
cc, config := newCustomClient(b, &hc.Client{
Secret: uuid.New().String(),
RedirectURIs: []string{public.URL + "/callback"},
ResponseTypes: []string{"token"},
GrantTypes: []string{"client_credentials"},
Scope: "foobar",
Audience: []string{"https://api.ory.sh/"},
})
return cc, config
}
var getToken = func(t *testing.B, conf clientcredentials.Config) (*goauth2.Token, error) {
conf.AuthStyle = goauth2.AuthStyleInHeader
return conf.Token(context.Background())
}
var encodeOr = func(b *testing.B, val interface{}, or string) string {
out, err := json.Marshal(val)
require.NoError(b, err)
if string(out) == "null" {
return or
}
return string(out)
}
var inspectToken = func(b *testing.B, token *goauth2.Token, cl *hc.Client, conf clientcredentials.Config, strategy string, expectedExp time.Time, checkExtraClaims bool) {
introspection := testhelpers.IntrospectToken(b, &goauth2.Config{ClientID: cl.GetID(), ClientSecret: conf.ClientSecret}, token.AccessToken, admin)
check := func(res gjson.Result) {
assert.EqualValues(b, cl.GetID(), res.Get("client_id").String(), "%s", res.Raw)
assert.EqualValues(b, cl.GetID(), res.Get("sub").String(), "%s", res.Raw)
assert.EqualValues(b, reg.Config().IssuerURL(ctx).String(), res.Get("iss").String(), "%s", res.Raw)
assert.EqualValues(b, res.Get("nbf").Int(), res.Get("iat").Int(), "%s", res.Raw)
requirex.EqualTime(b, expectedExp, time.Unix(res.Get("exp").Int(), 0), time.Second)
assert.EqualValues(b, encodeOr(b, conf.EndpointParams["audience"], "[]"), res.Get("aud").Raw, "%s", res.Raw)
if checkExtraClaims {
require.True(b, res.Get("ext.hooked").Bool())
}
}
check(introspection)
assert.True(b, introspection.Get("active").Bool())
assert.EqualValues(b, "access_token", introspection.Get("token_use").String())
assert.EqualValues(b, "Bearer", introspection.Get("token_type").String())
assert.EqualValues(b, strings.Join(conf.Scopes, " "), introspection.Get("scope").String(), "%s", introspection.Raw)
if strategy != "jwt" {
return
}
body, err := x.DecodeSegment(strings.Split(token.AccessToken, ".")[1])
require.NoError(b, err)
jwtClaims := gjson.ParseBytes(body)
assert.NotEmpty(b, jwtClaims.Get("jti").String())
assert.EqualValues(b, encodeOr(b, conf.Scopes, "[]"), jwtClaims.Get("scp").Raw, "%s", introspection.Raw)
check(jwtClaims)
}
var getAndInspectToken = func(b *testing.B, cl *hc.Client, conf clientcredentials.Config, strategy string, expectedExp time.Time, checkExtraClaims bool) {
token, err := getToken(b, conf)
require.NoError(b, err)
inspectToken(b, token, cl, conf, strategy, expectedExp, checkExtraClaims)
}
run := func(strategy string) func(b *testing.B) {
return func(t *testing.B) {
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
cl, conf := newClient(b)
getAndInspectToken(b, cl, conf, strategy, time.Now().Add(reg.Config().GetAccessTokenLifespan(ctx)), false)
}
}
b.Run("strategy=jwt", func(b *testing.B) {
initialDBSpans := dbSpans(spans)
for i := 0; i < b.N; i++ {
run("jwt")(b)
}
b.ReportMetric(0, "ns/op")
b.ReportMetric(float64(b.Elapsed().Milliseconds())/float64(b.N), "ms/op")
b.ReportMetric((float64(dbSpans(spans)-initialDBSpans))/float64(b.N), "queries/op")
})
b.Run("strategy=opaque", func(b *testing.B) {
initialDBSpans := dbSpans(spans)
for i := 0; i < b.N; i++ {
run("opaque")(b)
}
b.ReportMetric(0, "ns/op")
b.ReportMetric(float64(b.Elapsed().Milliseconds())/float64(b.N), "ms/op")
b.ReportMetric((float64(dbSpans(spans)-initialDBSpans))/float64(b.N), "queries/op")
})
}
func dbSpans(spans *tracetest.SpanRecorder) (count int) {
for _, s := range spans.Started() {
if strings.HasPrefix(s.Name(), "sql-") {
count++
}
}
return
} |
Go | hydra/oauth2/oauth2_client_credentials_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/tidwall/gjson"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
goauth2 "golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
"github.com/ory/hydra/v2/flow"
"github.com/ory/hydra/v2/internal/testhelpers"
hydraoauth2 "github.com/ory/hydra/v2/oauth2"
"github.com/ory/x/contextx"
hc "github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/internal"
"github.com/ory/hydra/v2/x"
"github.com/ory/x/requirex"
)
func TestClientCredentials(t *testing.T) {
ctx := context.Background()
reg := internal.NewMockedRegistry(t, &contextx.Default{})
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, "opaque")
public, admin := testhelpers.NewOAuth2Server(ctx, t, reg)
var newCustomClient = func(t *testing.T, c *hc.Client) (*hc.Client, clientcredentials.Config) {
unhashedSecret := c.Secret
require.NoError(t, reg.ClientManager().CreateClient(ctx, c))
return c, clientcredentials.Config{
ClientID: c.GetID(),
ClientSecret: unhashedSecret,
TokenURL: reg.Config().OAuth2TokenURL(ctx).String(),
Scopes: strings.Split(c.Scope, " "),
EndpointParams: url.Values{"audience": c.Audience},
}
}
var newClient = func(t *testing.T) (*hc.Client, clientcredentials.Config) {
cc, config := newCustomClient(t, &hc.Client{
Secret: uuid.New().String(),
RedirectURIs: []string{public.URL + "/callback"},
ResponseTypes: []string{"token"},
GrantTypes: []string{"client_credentials"},
Scope: "foobar",
Audience: []string{"https://api.ory.sh/"},
})
return cc, config
}
var getToken = func(t *testing.T, conf clientcredentials.Config) (*goauth2.Token, error) {
conf.AuthStyle = goauth2.AuthStyleInHeader
return conf.Token(context.Background())
}
var encodeOr = func(t *testing.T, val interface{}, or string) string {
out, err := json.Marshal(val)
require.NoError(t, err)
if string(out) == "null" {
return or
}
return string(out)
}
var inspectToken = func(t *testing.T, token *goauth2.Token, cl *hc.Client, conf clientcredentials.Config, strategy string, expectedExp time.Time, checkExtraClaims bool) {
introspection := testhelpers.IntrospectToken(t, &goauth2.Config{ClientID: cl.GetID(), ClientSecret: conf.ClientSecret}, token.AccessToken, admin)
check := func(res gjson.Result) {
assert.EqualValues(t, cl.GetID(), res.Get("client_id").String(), "%s", res.Raw)
assert.EqualValues(t, cl.GetID(), res.Get("sub").String(), "%s", res.Raw)
assert.EqualValues(t, reg.Config().IssuerURL(ctx).String(), res.Get("iss").String(), "%s", res.Raw)
assert.EqualValues(t, res.Get("nbf").Int(), res.Get("iat").Int(), "%s", res.Raw)
requirex.EqualTime(t, expectedExp, time.Unix(res.Get("exp").Int(), 0), time.Second)
assert.EqualValues(t, encodeOr(t, conf.EndpointParams["audience"], "[]"), res.Get("aud").Raw, "%s", res.Raw)
if checkExtraClaims {
require.True(t, res.Get("ext.hooked").Bool())
}
}
check(introspection)
assert.True(t, introspection.Get("active").Bool())
assert.EqualValues(t, "access_token", introspection.Get("token_use").String())
assert.EqualValues(t, "Bearer", introspection.Get("token_type").String())
assert.EqualValues(t, strings.Join(conf.Scopes, " "), introspection.Get("scope").String(), "%s", introspection.Raw)
if strategy != "jwt" {
return
}
body, err := x.DecodeSegment(strings.Split(token.AccessToken, ".")[1])
require.NoError(t, err)
jwtClaims := gjson.ParseBytes(body)
assert.NotEmpty(t, jwtClaims.Get("jti").String())
assert.EqualValues(t, encodeOr(t, conf.Scopes, "[]"), jwtClaims.Get("scp").Raw, "%s", introspection.Raw)
check(jwtClaims)
}
var getAndInspectToken = func(t *testing.T, cl *hc.Client, conf clientcredentials.Config, strategy string, expectedExp time.Time, checkExtraClaims bool) {
token, err := getToken(t, conf)
require.NoError(t, err)
inspectToken(t, token, cl, conf, strategy, expectedExp, checkExtraClaims)
}
t.Run("case=should fail because audience is not allowed", func(t *testing.T) {
_, conf := newClient(t)
conf.EndpointParams = url.Values{"audience": {"https://not-api.ory.sh/"}}
_, err := getToken(t, conf)
require.Error(t, err)
})
t.Run("case=should fail because scope is not allowed", func(t *testing.T) {
_, conf := newClient(t)
conf.Scopes = []string{"not-allowed-scope"}
_, err := getToken(t, conf)
require.Error(t, err)
})
t.Run("case=should pass with audience", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
cl, conf := newClient(t)
getAndInspectToken(t, cl, conf, strategy, time.Now().Add(reg.Config().GetAccessTokenLifespan(ctx)), false)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("case=should pass without audience", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
cl, conf := newClient(t)
conf.EndpointParams = url.Values{}
getAndInspectToken(t, cl, conf, strategy, time.Now().Add(reg.Config().GetAccessTokenLifespan(ctx)), false)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("case=should pass without scope", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
cl, conf := newClient(t)
conf.Scopes = []string{}
getAndInspectToken(t, cl, conf, strategy, time.Now().Add(reg.Config().GetAccessTokenLifespan(ctx)), false)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("case=should grant default scopes if configured to do ", func(t *testing.T) {
reg.Config().MustSet(ctx, config.KeyGrantAllClientCredentialsScopesPerDefault, true)
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
cl, conf := newClient(t)
defaultScope := conf.Scopes
conf.Scopes = []string{}
token, err := getToken(t, conf)
require.NoError(t, err)
// We reset this so that introspectToken is going to check for the default scope.
conf.Scopes = defaultScope
inspectToken(t, token, cl, conf, strategy, time.Now().Add(reg.Config().GetAccessTokenLifespan(ctx)), false)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("case=should pass with custom client access token lifespan", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
secret := uuid.New().String()
cl, conf := newCustomClient(t, &hc.Client{
Secret: secret,
RedirectURIs: []string{public.URL + "/callback"},
ResponseTypes: []string{"token"},
GrantTypes: []string{"client_credentials"},
Scope: "foobar",
Audience: []string{"https://api.ory.sh/"},
})
testhelpers.UpdateClientTokenLifespans(t, &goauth2.Config{ClientID: cl.GetID(), ClientSecret: conf.ClientSecret}, cl.GetID(), testhelpers.TestLifespans, admin)
getAndInspectToken(t, cl, conf, strategy, time.Now().Add(testhelpers.TestLifespans.ClientCredentialsGrantAccessTokenLifespan.Duration), false)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("case=should respect TTL", func(t *testing.T) {
duration := time.Hour * 24 * 7
reg.Config().MustSet(ctx, config.KeyAccessTokenLifespan, duration.String())
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
cl, conf := newClient(t)
conf.Scopes = []string{}
token, err := getToken(t, conf)
require.NoError(t, err)
expected := time.Now().Add(duration)
assert.WithinDuration(t, expected, token.Expiry, 5*time.Second)
introspection := testhelpers.IntrospectToken(t, &goauth2.Config{ClientID: cl.GetID(), ClientSecret: conf.ClientSecret}, token.AccessToken, admin)
assert.WithinDuration(t, expected, time.Unix(introspection.Get("exp").Int(), 0), 5*time.Second)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("should call token hook if configured", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
scope := "foobar"
audience := []string{"https://api.ory.sh/"}
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, r.Header.Get("Content-Type"), "application/json; charset=UTF-8")
expectedGrantedScopes := []string{"foobar"}
expectedGrantedAudience := []string{"https://api.ory.sh/"}
var hookReq hydraoauth2.TokenHookRequest
require.NoError(t, json.NewDecoder(r.Body).Decode(&hookReq))
require.NotEmpty(t, hookReq.Session)
require.Equal(t, hookReq.Session.Extra, map[string]interface{}{})
require.NotEmpty(t, hookReq.Request)
require.ElementsMatch(t, hookReq.Request.GrantedScopes, expectedGrantedScopes)
require.ElementsMatch(t, hookReq.Request.GrantedAudience, expectedGrantedAudience)
require.Equal(t, hookReq.Request.Payload, map[string][]string{})
claims := map[string]interface{}{
"hooked": true,
}
hookResp := hydraoauth2.TokenHookResponse{
Session: flow.AcceptOAuth2ConsentRequestSession{
AccessToken: claims,
IDToken: claims,
},
}
w.WriteHeader(http.StatusOK)
require.NoError(t, json.NewEncoder(w).Encode(&hookResp))
}))
defer hs.Close()
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil)
secret := uuid.New().String()
cl, conf := newCustomClient(t, &hc.Client{
Secret: secret,
RedirectURIs: []string{public.URL + "/callback"},
ResponseTypes: []string{"token"},
GrantTypes: []string{"client_credentials"},
Scope: scope,
Audience: audience,
})
getAndInspectToken(t, cl, conf, strategy, time.Now().Add(reg.Config().GetAccessTokenLifespan(ctx)), true)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("should fail token if hook fails", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer hs.Close()
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil)
_, conf := newClient(t)
_, err := getToken(t, conf)
require.Error(t, err)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("should fail token if hook denied the request", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
}))
defer hs.Close()
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil)
_, conf := newClient(t)
_, err := getToken(t, conf)
require.Error(t, err)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("should fail token if hook response is malformed", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer hs.Close()
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil)
_, conf := newClient(t)
_, err := getToken(t, conf)
require.Error(t, err)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
} |
Go | hydra/oauth2/oauth2_helper_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2_test
import (
"context"
"net/http"
"time"
"github.com/pkg/errors"
"github.com/ory/fosite"
"github.com/ory/hydra/v2/flow"
"github.com/ory/x/sqlxx"
"github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/consent"
)
var _ consent.Strategy = new(consentMock)
type consentMock struct {
deny bool
authTime time.Time
requestTime time.Time
}
func (c *consentMock) HandleOAuth2AuthorizationRequest(ctx context.Context, w http.ResponseWriter, r *http.Request, req fosite.AuthorizeRequester) (*flow.AcceptOAuth2ConsentRequest, *flow.Flow, error) {
if c.deny {
return nil, nil, fosite.ErrRequestForbidden
}
return &flow.AcceptOAuth2ConsentRequest{
ConsentRequest: &flow.OAuth2ConsentRequest{
Subject: "foo",
ACR: "1",
},
AuthenticatedAt: sqlxx.NullTime(c.authTime),
GrantedScope: []string{"offline", "openid", "hydra.*"},
Session: &flow.AcceptOAuth2ConsentRequestSession{
AccessToken: map[string]interface{}{},
IDToken: map[string]interface{}{},
},
RequestedAt: c.requestTime,
}, nil, nil
}
func (c *consentMock) HandleOpenIDConnectLogout(ctx context.Context, w http.ResponseWriter, r *http.Request) (*flow.LogoutResult, error) {
panic("not implemented")
}
func (c *consentMock) HandleHeadlessLogout(ctx context.Context, w http.ResponseWriter, r *http.Request, sid string) error {
panic("not implemented")
}
func (c *consentMock) ObfuscateSubjectIdentifier(ctx context.Context, cl fosite.Client, subject, forcedIdentifier string) (string, error) {
if c, ok := cl.(*client.Client); ok && c.SubjectType == "pairwise" {
panic("not implemented")
} else if !ok {
return "", errors.New("Unable to type assert OAuth 2.0 Client to *client.Client")
}
return subject, nil
} |
Go | hydra/oauth2/oauth2_jwt_bearer_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2_test
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/go-jose/go-jose/v3"
"github.com/google/uuid"
"github.com/tidwall/gjson"
"github.com/ory/fosite/token/jwt"
"github.com/ory/hydra/v2/flow"
"github.com/ory/hydra/v2/jwk"
hydraoauth2 "github.com/ory/hydra/v2/oauth2"
"github.com/ory/hydra/v2/oauth2/trust"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
goauth2 "golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
"github.com/ory/hydra/v2/internal/testhelpers"
"github.com/ory/x/contextx"
hc "github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/internal"
"github.com/ory/hydra/v2/x"
)
func TestJWTBearer(t *testing.T) {
ctx := context.Background()
reg := internal.NewMockedRegistry(t, &contextx.Default{})
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, "opaque")
_, admin := testhelpers.NewOAuth2Server(ctx, t, reg)
secret := uuid.New().String()
client := &hc.Client{
Secret: secret,
GrantTypes: []string{"client_credentials", "urn:ietf:params:oauth:grant-type:jwt-bearer"},
Scope: "offline_access",
}
require.NoError(t, reg.ClientManager().CreateClient(ctx, client))
newConf := func(client *hc.Client) *clientcredentials.Config {
return &clientcredentials.Config{
ClientID: client.GetID(),
ClientSecret: secret,
TokenURL: reg.Config().OAuth2TokenURL(ctx).String(),
Scopes: strings.Split(client.Scope, " "),
EndpointParams: url.Values{"audience": client.Audience},
}
}
var getToken = func(t *testing.T, conf *clientcredentials.Config) (*goauth2.Token, error) {
if conf.AuthStyle == goauth2.AuthStyleAutoDetect {
conf.AuthStyle = goauth2.AuthStyleInHeader
}
return conf.Token(context.Background())
}
var inspectToken = func(t *testing.T, token *goauth2.Token, cl *hc.Client, strategy string, grant trust.Grant, checkExtraClaims bool) {
introspection := testhelpers.IntrospectToken(t, &goauth2.Config{ClientID: cl.GetID(), ClientSecret: cl.Secret}, token.AccessToken, admin)
check := func(res gjson.Result) {
assert.EqualValues(t, cl.GetID(), res.Get("client_id").String(), "%s", res.Raw)
assert.EqualValues(t, grant.Subject, res.Get("sub").String(), "%s", res.Raw)
assert.EqualValues(t, reg.Config().IssuerURL(ctx).String(), res.Get("iss").String(), "%s", res.Raw)
assert.EqualValues(t, res.Get("nbf").Int(), res.Get("iat").Int(), "%s", res.Raw)
assert.True(t, res.Get("exp").Int() >= res.Get("iat").Int()+int64(reg.Config().GetAccessTokenLifespan(ctx).Seconds()), "%s", res.Raw)
assert.EqualValues(t, fmt.Sprintf(`["%s"]`, reg.Config().OAuth2TokenURL(ctx).String()), res.Get("aud").Raw, "%s", res.Raw)
if checkExtraClaims {
require.True(t, res.Get("ext.hooked").Bool())
}
}
check(introspection)
assert.True(t, introspection.Get("active").Bool())
assert.EqualValues(t, "access_token", introspection.Get("token_use").String())
assert.EqualValues(t, "Bearer", introspection.Get("token_type").String())
assert.EqualValues(t, "offline_access", introspection.Get("scope").String(), "%s", introspection.Raw)
if strategy != "jwt" {
return
}
body, err := x.DecodeSegment(strings.Split(token.AccessToken, ".")[1])
require.NoError(t, err)
jwtClaims := gjson.ParseBytes(body)
assert.NotEmpty(t, jwtClaims.Get("jti").String())
assert.NotEmpty(t, jwtClaims.Get("iss").String())
assert.NotEmpty(t, jwtClaims.Get("client_id").String())
assert.EqualValues(t, "offline_access", introspection.Get("scope").String(), "%s", introspection.Raw)
header, err := x.DecodeSegment(strings.Split(token.AccessToken, ".")[0])
require.NoError(t, err)
jwtHeader := gjson.ParseBytes(header)
assert.NotEmpty(t, jwtHeader.Get("kid").String())
assert.EqualValues(t, "offline_access", introspection.Get("scope").String(), "%s", introspection.Raw)
check(jwtClaims)
}
t.Run("case=unable to exchange invalid jwt", func(t *testing.T) {
conf := newConf(client)
conf.EndpointParams = url.Values{"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"}, "assertion": {"not-a-jwt"}}
_, err := getToken(t, conf)
require.Error(t, err)
assert.Contains(t, err.Error(), "Unable to parse JSON Web Token")
})
t.Run("case=unable to request grant if not set", func(t *testing.T) {
client := &hc.Client{
Secret: secret,
GrantTypes: []string{"client_credentials"},
Scope: "offline_access",
}
require.NoError(t, reg.ClientManager().CreateClient(ctx, client))
conf := newConf(client)
conf.EndpointParams = url.Values{"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"}, "assertion": {"not-a-jwt"}}
_, err := getToken(t, conf)
require.Error(t, err)
assert.Contains(t, err.Error(), "urn:ietf:params:oauth:grant-type:jwt-bearer")
})
set, kid := uuid.NewString(), uuid.NewString()
keys, err := jwk.GenerateJWK(ctx, jose.RS256, kid, "sig")
require.NoError(t, err)
trustGrant := trust.Grant{
ID: uuid.NewString(),
Issuer: set,
Subject: uuid.NewString(),
AllowAnySubject: false,
Scope: []string{"offline_access"},
ExpiresAt: time.Now().Add(time.Hour),
PublicKey: trust.PublicKey{Set: set, KeyID: kid},
}
require.NoError(t, reg.GrantManager().CreateGrant(ctx, trustGrant, keys.Keys[0].Public()))
signer := jwk.NewDefaultJWTSigner(reg.Config(), reg, set)
signer.GetPrivateKey = func(ctx context.Context) (interface{}, error) {
return keys.Keys[0], nil
}
t.Run("case=unable to exchange token with a non-allowed subject", func(t *testing.T) {
token, _, err := signer.Generate(ctx, jwt.MapClaims{
"jti": uuid.NewString(),
"iss": trustGrant.Issuer,
"sub": uuid.NewString(),
"aud": reg.Config().OAuth2TokenURL(ctx).String(),
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Add(-time.Minute).Unix(),
}, &jwt.Headers{Extra: map[string]interface{}{"kid": kid}})
require.NoError(t, err)
conf := newConf(client)
conf.EndpointParams = url.Values{"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"}, "assertion": {token}}
_, err = getToken(t, conf)
require.Error(t, err)
assert.Contains(t, err.Error(), "public key is required to check signature of JWT")
})
t.Run("case=unable to exchange token with non-allowed scope", func(t *testing.T) {
token, _, err := signer.Generate(ctx, jwt.MapClaims{
"jti": uuid.NewString(),
"iss": trustGrant.Issuer,
"sub": trustGrant.Subject,
"aud": reg.Config().OAuth2TokenURL(ctx).String(),
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Add(-time.Minute).Unix(),
}, &jwt.Headers{Extra: map[string]interface{}{"kid": kid}})
require.NoError(t, err)
conf := newConf(client)
conf.Scopes = []string{"i_am_not_allowed"}
conf.EndpointParams = url.Values{"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"}, "assertion": {token}}
_, err = getToken(t, conf)
require.Error(t, err)
assert.Contains(t, err.Error(), "i_am_not_allowed")
})
t.Run("case=unable to exchange token with an unknown kid", func(t *testing.T) {
token, _, err := signer.Generate(ctx, jwt.MapClaims{
"jti": uuid.NewString(),
"iss": trustGrant.Issuer,
"sub": trustGrant.Subject,
"aud": reg.Config().OAuth2TokenURL(ctx).String(),
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Add(-time.Minute).Unix(),
}, &jwt.Headers{Extra: map[string]interface{}{"kid": uuid.NewString()}})
require.NoError(t, err)
conf := newConf(client)
conf.EndpointParams = url.Values{"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"}, "assertion": {token}}
_, err = getToken(t, conf)
require.Error(t, err)
assert.Contains(t, err.Error(), "public key is required to check signature of JWT")
})
t.Run("case=unable to exchange token with an invalid key", func(t *testing.T) {
keys, err := jwk.GenerateJWK(ctx, jose.RS256, kid, "sig")
require.NoError(t, err)
signer := jwk.NewDefaultJWTSigner(reg.Config(), reg, set)
signer.GetPrivateKey = func(ctx context.Context) (interface{}, error) {
return keys.Keys[0], nil
}
token, _, err := signer.Generate(ctx, jwt.MapClaims{
"jti": uuid.NewString(),
"iss": trustGrant.Issuer,
"sub": trustGrant.Subject,
"aud": reg.Config().OAuth2TokenURL(ctx).String(),
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Add(-time.Minute).Unix(),
}, &jwt.Headers{Extra: map[string]interface{}{"kid": kid}})
require.NoError(t, err)
conf := newConf(client)
conf.EndpointParams = url.Values{"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"}, "assertion": {token}}
_, err = getToken(t, conf)
require.Error(t, err)
assert.Contains(t, err.Error(), "Unable to verify the integrity")
})
t.Run("case=should exchange for an access token", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
token, _, err := signer.Generate(ctx, jwt.MapClaims{
"jti": uuid.NewString(),
"iss": trustGrant.Issuer,
"sub": trustGrant.Subject,
"aud": reg.Config().OAuth2TokenURL(ctx).String(),
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Add(-time.Minute).Unix(),
}, &jwt.Headers{Extra: map[string]interface{}{"kid": kid}})
require.NoError(t, err)
conf := newConf(client)
conf.EndpointParams = url.Values{"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"}, "assertion": {token}}
result, err := getToken(t, conf)
require.NoError(t, err)
inspectToken(t, result, client, strategy, trustGrant, false)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("case=exchange for an access token without client", func(t *testing.T) {
t.Skip("This currently does not work because the client is a required foreign key and also required throughout the code base.")
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
reg.Config().MustSet(ctx, "config.KeyOAuth2GrantJWTClientAuthOptional", true)
token, _, err := signer.Generate(ctx, jwt.MapClaims{
"jti": uuid.NewString(),
"iss": trustGrant.Issuer,
"sub": trustGrant.Subject,
"aud": reg.Config().OAuth2TokenURL(ctx).String(),
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Add(-time.Minute).Unix(),
}, &jwt.Headers{Extra: map[string]interface{}{"kid": kid}})
require.NoError(t, err)
res, err := http.DefaultClient.PostForm(reg.Config().OAuth2TokenURL(ctx).String(), url.Values{
"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"},
"assertion": {token},
})
require.NoError(t, err)
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
require.EqualValues(t, http.StatusOK, res.StatusCode, "%s", body)
var result goauth2.Token
require.NoError(t, json.Unmarshal(body, &result))
assert.NotEmpty(t, result.AccessToken, "%s", body)
inspectToken(t, &result, client, strategy, trustGrant, false)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("should call token hook if configured", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
audience := reg.Config().OAuth2TokenURL(ctx).String()
grantType := "urn:ietf:params:oauth:grant-type:jwt-bearer"
token, _, err := signer.Generate(ctx, jwt.MapClaims{
"jti": uuid.NewString(),
"iss": trustGrant.Issuer,
"sub": trustGrant.Subject,
"aud": audience,
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Add(-time.Minute).Unix(),
}, &jwt.Headers{Extra: map[string]interface{}{"kid": kid}})
require.NoError(t, err)
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, r.Header.Get("Content-Type"), "application/json; charset=UTF-8")
expectedGrantedScopes := []string{client.Scope}
expectedGrantedAudience := []string{audience}
expectedPayload := map[string][]string(map[string][]string{"assertion": {token}})
var hookReq hydraoauth2.TokenHookRequest
require.NoError(t, json.NewDecoder(r.Body).Decode(&hookReq))
require.NotEmpty(t, hookReq.Session)
require.Equal(t, hookReq.Session.Extra, map[string]interface{}{})
require.NotEmpty(t, hookReq.Request)
require.ElementsMatch(t, hookReq.Request.GrantedScopes, expectedGrantedScopes)
require.ElementsMatch(t, hookReq.Request.GrantedAudience, expectedGrantedAudience)
require.Equal(t, hookReq.Request.Payload, expectedPayload)
claims := map[string]interface{}{
"hooked": true,
}
hookResp := hydraoauth2.TokenHookResponse{
Session: flow.AcceptOAuth2ConsentRequestSession{
AccessToken: claims,
IDToken: claims,
},
}
w.WriteHeader(http.StatusOK)
require.NoError(t, json.NewEncoder(w).Encode(&hookResp))
}))
defer hs.Close()
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil)
conf := newConf(client)
conf.EndpointParams = url.Values{"grant_type": {grantType}, "assertion": {token}}
result, err := getToken(t, conf)
require.NoError(t, err)
inspectToken(t, result, client, strategy, trustGrant, true)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("should call token hook if configured and omit client_secret from payload", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
audience := reg.Config().OAuth2TokenURL(ctx).String()
grantType := "urn:ietf:params:oauth:grant-type:jwt-bearer"
token, _, err := signer.Generate(ctx, jwt.MapClaims{
"jti": uuid.NewString(),
"iss": trustGrant.Issuer,
"sub": trustGrant.Subject,
"aud": audience,
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Add(-time.Minute).Unix(),
}, &jwt.Headers{Extra: map[string]interface{}{"kid": kid}})
require.NoError(t, err)
client := &hc.Client{
Secret: secret,
GrantTypes: []string{"urn:ietf:params:oauth:grant-type:jwt-bearer"},
Scope: "offline_access",
TokenEndpointAuthMethod: "client_secret_post",
}
require.NoError(t, reg.ClientManager().CreateClient(ctx, client))
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, r.Header.Get("Content-Type"), "application/json; charset=UTF-8")
expectedGrantedScopes := []string{client.Scope}
expectedGrantedAudience := []string{audience}
expectedPayload := map[string][]string(map[string][]string{"assertion": {token}})
var hookReq hydraoauth2.TokenHookRequest
require.NoError(t, json.NewDecoder(r.Body).Decode(&hookReq))
require.NotEmpty(t, hookReq.Session)
require.Equal(t, hookReq.Session.Extra, map[string]interface{}{})
require.NotEmpty(t, hookReq.Request)
require.ElementsMatch(t, hookReq.Request.GrantedScopes, expectedGrantedScopes)
require.ElementsMatch(t, hookReq.Request.GrantedAudience, expectedGrantedAudience)
require.Equal(t, hookReq.Request.Payload, expectedPayload)
claims := map[string]interface{}{
"hooked": true,
}
hookResp := hydraoauth2.TokenHookResponse{
Session: flow.AcceptOAuth2ConsentRequestSession{
AccessToken: claims,
IDToken: claims,
},
}
w.WriteHeader(http.StatusOK)
require.NoError(t, json.NewEncoder(w).Encode(&hookResp))
}))
defer hs.Close()
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil)
conf := newConf(client)
conf.AuthStyle = goauth2.AuthStyleInParams
conf.EndpointParams = url.Values{"grant_type": {grantType}, "assertion": {token}}
result, err := getToken(t, conf)
require.NoError(t, err)
inspectToken(t, result, client, strategy, trustGrant, true)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("should fail token if hook fails", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer hs.Close()
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil)
token, _, err := signer.Generate(ctx, jwt.MapClaims{
"jti": uuid.NewString(),
"iss": trustGrant.Issuer,
"sub": trustGrant.Subject,
"aud": reg.Config().OAuth2TokenURL(ctx).String(),
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Add(-time.Minute).Unix(),
}, &jwt.Headers{Extra: map[string]interface{}{"kid": kid}})
require.NoError(t, err)
conf := newConf(client)
conf.EndpointParams = url.Values{"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"}, "assertion": {token}}
_, tokenError := getToken(t, conf)
require.Error(t, tokenError)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("should fail token if hook denied the request", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
}))
defer hs.Close()
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil)
token, _, err := signer.Generate(ctx, jwt.MapClaims{
"jti": uuid.NewString(),
"iss": trustGrant.Issuer,
"sub": trustGrant.Subject,
"aud": reg.Config().OAuth2TokenURL(ctx).String(),
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Add(-time.Minute).Unix(),
}, &jwt.Headers{Extra: map[string]interface{}{"kid": kid}})
require.NoError(t, err)
conf := newConf(client)
conf.EndpointParams = url.Values{"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"}, "assertion": {token}}
_, tokenError := getToken(t, conf)
require.Error(t, tokenError)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
t.Run("should fail token if hook response is malformed", func(t *testing.T) {
run := func(strategy string) func(t *testing.T) {
return func(t *testing.T) {
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer hs.Close()
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy)
reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL)
defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil)
token, _, err := signer.Generate(ctx, jwt.MapClaims{
"jti": uuid.NewString(),
"iss": trustGrant.Issuer,
"sub": trustGrant.Subject,
"aud": reg.Config().OAuth2TokenURL(ctx).String(),
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Add(-time.Minute).Unix(),
}, &jwt.Headers{Extra: map[string]interface{}{"kid": kid}})
require.NoError(t, err)
conf := newConf(client)
conf.EndpointParams = url.Values{"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"}, "assertion": {token}}
_, tokenError := getToken(t, conf)
require.Error(t, tokenError)
}
}
t.Run("strategy=opaque", run("opaque"))
t.Run("strategy=jwt", run("jwt"))
})
} |
Go | hydra/oauth2/oauth2_provider_mock_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
// Code generated by MockGen. DO NOT EDIT.
// Source: github.com/ory/fosite (interfaces: OAuth2Provider)
// Package oauth2_test is a generated GoMock package.
package oauth2_test
import (
context "context"
http "net/http"
reflect "reflect"
gomock "github.com/golang/mock/gomock"
fosite "github.com/ory/fosite"
)
// MockOAuth2Provider is a mock of OAuth2Provider interface.
type MockOAuth2Provider struct {
ctrl *gomock.Controller
recorder *MockOAuth2ProviderMockRecorder
}
// MockOAuth2ProviderMockRecorder is the mock recorder for MockOAuth2Provider.
type MockOAuth2ProviderMockRecorder struct {
mock *MockOAuth2Provider
}
// NewMockOAuth2Provider creates a new mock instance.
func NewMockOAuth2Provider(ctrl *gomock.Controller) *MockOAuth2Provider {
mock := &MockOAuth2Provider{ctrl: ctrl}
mock.recorder = &MockOAuth2ProviderMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockOAuth2Provider) EXPECT() *MockOAuth2ProviderMockRecorder {
return m.recorder
}
// IntrospectToken mocks base method.
func (m *MockOAuth2Provider) IntrospectToken(arg0 context.Context, arg1 string, arg2 fosite.TokenType, arg3 fosite.Session, arg4 ...string) (fosite.TokenType, fosite.AccessRequester, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1, arg2, arg3}
for _, a := range arg4 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "IntrospectToken", varargs...)
ret0, _ := ret[0].(fosite.TokenType)
ret1, _ := ret[1].(fosite.AccessRequester)
ret2, _ := ret[2].(error)
return ret0, ret1, ret2
}
// IntrospectToken indicates an expected call of IntrospectToken.
func (mr *MockOAuth2ProviderMockRecorder) IntrospectToken(arg0, arg1, arg2, arg3 interface{}, arg4 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1, arg2, arg3}, arg4...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IntrospectToken", reflect.TypeOf((*MockOAuth2Provider)(nil).IntrospectToken), varargs...)
}
// NewAccessRequest mocks base method.
func (m *MockOAuth2Provider) NewAccessRequest(arg0 context.Context, arg1 *http.Request, arg2 fosite.Session) (fosite.AccessRequester, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NewAccessRequest", arg0, arg1, arg2)
ret0, _ := ret[0].(fosite.AccessRequester)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// NewAccessRequest indicates an expected call of NewAccessRequest.
func (mr *MockOAuth2ProviderMockRecorder) NewAccessRequest(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewAccessRequest", reflect.TypeOf((*MockOAuth2Provider)(nil).NewAccessRequest), arg0, arg1, arg2)
}
// NewAccessResponse mocks base method.
func (m *MockOAuth2Provider) NewAccessResponse(arg0 context.Context, arg1 fosite.AccessRequester) (fosite.AccessResponder, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NewAccessResponse", arg0, arg1)
ret0, _ := ret[0].(fosite.AccessResponder)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// NewAccessResponse indicates an expected call of NewAccessResponse.
func (mr *MockOAuth2ProviderMockRecorder) NewAccessResponse(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewAccessResponse", reflect.TypeOf((*MockOAuth2Provider)(nil).NewAccessResponse), arg0, arg1)
}
// NewAuthorizeRequest mocks base method.
func (m *MockOAuth2Provider) NewAuthorizeRequest(arg0 context.Context, arg1 *http.Request) (fosite.AuthorizeRequester, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NewAuthorizeRequest", arg0, arg1)
ret0, _ := ret[0].(fosite.AuthorizeRequester)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// NewAuthorizeRequest indicates an expected call of NewAuthorizeRequest.
func (mr *MockOAuth2ProviderMockRecorder) NewAuthorizeRequest(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewAuthorizeRequest", reflect.TypeOf((*MockOAuth2Provider)(nil).NewAuthorizeRequest), arg0, arg1)
}
// NewAuthorizeResponse mocks base method.
func (m *MockOAuth2Provider) NewAuthorizeResponse(arg0 context.Context, arg1 fosite.AuthorizeRequester, arg2 fosite.Session) (fosite.AuthorizeResponder, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NewAuthorizeResponse", arg0, arg1, arg2)
ret0, _ := ret[0].(fosite.AuthorizeResponder)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// NewAuthorizeResponse indicates an expected call of NewAuthorizeResponse.
func (mr *MockOAuth2ProviderMockRecorder) NewAuthorizeResponse(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewAuthorizeResponse", reflect.TypeOf((*MockOAuth2Provider)(nil).NewAuthorizeResponse), arg0, arg1, arg2)
}
// NewIntrospectionRequest mocks base method.
func (m *MockOAuth2Provider) NewIntrospectionRequest(arg0 context.Context, arg1 *http.Request, arg2 fosite.Session) (fosite.IntrospectionResponder, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NewIntrospectionRequest", arg0, arg1, arg2)
ret0, _ := ret[0].(fosite.IntrospectionResponder)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// NewIntrospectionRequest indicates an expected call of NewIntrospectionRequest.
func (mr *MockOAuth2ProviderMockRecorder) NewIntrospectionRequest(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewIntrospectionRequest", reflect.TypeOf((*MockOAuth2Provider)(nil).NewIntrospectionRequest), arg0, arg1, arg2)
}
// NewPushedAuthorizeRequest mocks base method.
func (m *MockOAuth2Provider) NewPushedAuthorizeRequest(arg0 context.Context, arg1 *http.Request) (fosite.AuthorizeRequester, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NewPushedAuthorizeRequest", arg0, arg1)
ret0, _ := ret[0].(fosite.AuthorizeRequester)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// NewPushedAuthorizeRequest indicates an expected call of NewPushedAuthorizeRequest.
func (mr *MockOAuth2ProviderMockRecorder) NewPushedAuthorizeRequest(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewPushedAuthorizeRequest", reflect.TypeOf((*MockOAuth2Provider)(nil).NewPushedAuthorizeRequest), arg0, arg1)
}
// NewPushedAuthorizeResponse mocks base method.
func (m *MockOAuth2Provider) NewPushedAuthorizeResponse(arg0 context.Context, arg1 fosite.AuthorizeRequester, arg2 fosite.Session) (fosite.PushedAuthorizeResponder, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NewPushedAuthorizeResponse", arg0, arg1, arg2)
ret0, _ := ret[0].(fosite.PushedAuthorizeResponder)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// NewPushedAuthorizeResponse indicates an expected call of NewPushedAuthorizeResponse.
func (mr *MockOAuth2ProviderMockRecorder) NewPushedAuthorizeResponse(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewPushedAuthorizeResponse", reflect.TypeOf((*MockOAuth2Provider)(nil).NewPushedAuthorizeResponse), arg0, arg1, arg2)
}
// NewRevocationRequest mocks base method.
func (m *MockOAuth2Provider) NewRevocationRequest(arg0 context.Context, arg1 *http.Request) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NewRevocationRequest", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
// NewRevocationRequest indicates an expected call of NewRevocationRequest.
func (mr *MockOAuth2ProviderMockRecorder) NewRevocationRequest(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewRevocationRequest", reflect.TypeOf((*MockOAuth2Provider)(nil).NewRevocationRequest), arg0, arg1)
}
// WriteAccessError mocks base method.
func (m *MockOAuth2Provider) WriteAccessError(arg0 context.Context, arg1 http.ResponseWriter, arg2 fosite.AccessRequester, arg3 error) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "WriteAccessError", arg0, arg1, arg2, arg3)
}
// WriteAccessError indicates an expected call of WriteAccessError.
func (mr *MockOAuth2ProviderMockRecorder) WriteAccessError(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WriteAccessError", reflect.TypeOf((*MockOAuth2Provider)(nil).WriteAccessError), arg0, arg1, arg2, arg3)
}
// WriteAccessResponse mocks base method.
func (m *MockOAuth2Provider) WriteAccessResponse(arg0 context.Context, arg1 http.ResponseWriter, arg2 fosite.AccessRequester, arg3 fosite.AccessResponder) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "WriteAccessResponse", arg0, arg1, arg2, arg3)
}
// WriteAccessResponse indicates an expected call of WriteAccessResponse.
func (mr *MockOAuth2ProviderMockRecorder) WriteAccessResponse(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WriteAccessResponse", reflect.TypeOf((*MockOAuth2Provider)(nil).WriteAccessResponse), arg0, arg1, arg2, arg3)
}
// WriteAuthorizeError mocks base method.
func (m *MockOAuth2Provider) WriteAuthorizeError(arg0 context.Context, arg1 http.ResponseWriter, arg2 fosite.AuthorizeRequester, arg3 error) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "WriteAuthorizeError", arg0, arg1, arg2, arg3)
}
// WriteAuthorizeError indicates an expected call of WriteAuthorizeError.
func (mr *MockOAuth2ProviderMockRecorder) WriteAuthorizeError(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WriteAuthorizeError", reflect.TypeOf((*MockOAuth2Provider)(nil).WriteAuthorizeError), arg0, arg1, arg2, arg3)
}
// WriteAuthorizeResponse mocks base method.
func (m *MockOAuth2Provider) WriteAuthorizeResponse(arg0 context.Context, arg1 http.ResponseWriter, arg2 fosite.AuthorizeRequester, arg3 fosite.AuthorizeResponder) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "WriteAuthorizeResponse", arg0, arg1, arg2, arg3)
}
// WriteAuthorizeResponse indicates an expected call of WriteAuthorizeResponse.
func (mr *MockOAuth2ProviderMockRecorder) WriteAuthorizeResponse(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WriteAuthorizeResponse", reflect.TypeOf((*MockOAuth2Provider)(nil).WriteAuthorizeResponse), arg0, arg1, arg2, arg3)
}
// WriteIntrospectionError mocks base method.
func (m *MockOAuth2Provider) WriteIntrospectionError(arg0 context.Context, arg1 http.ResponseWriter, arg2 error) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "WriteIntrospectionError", arg0, arg1, arg2)
}
// WriteIntrospectionError indicates an expected call of WriteIntrospectionError.
func (mr *MockOAuth2ProviderMockRecorder) WriteIntrospectionError(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WriteIntrospectionError", reflect.TypeOf((*MockOAuth2Provider)(nil).WriteIntrospectionError), arg0, arg1, arg2)
}
// WriteIntrospectionResponse mocks base method.
func (m *MockOAuth2Provider) WriteIntrospectionResponse(arg0 context.Context, arg1 http.ResponseWriter, arg2 fosite.IntrospectionResponder) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "WriteIntrospectionResponse", arg0, arg1, arg2)
}
// WriteIntrospectionResponse indicates an expected call of WriteIntrospectionResponse.
func (mr *MockOAuth2ProviderMockRecorder) WriteIntrospectionResponse(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WriteIntrospectionResponse", reflect.TypeOf((*MockOAuth2Provider)(nil).WriteIntrospectionResponse), arg0, arg1, arg2)
}
// WritePushedAuthorizeError mocks base method.
func (m *MockOAuth2Provider) WritePushedAuthorizeError(arg0 context.Context, arg1 http.ResponseWriter, arg2 fosite.AuthorizeRequester, arg3 error) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "WritePushedAuthorizeError", arg0, arg1, arg2, arg3)
}
// WritePushedAuthorizeError indicates an expected call of WritePushedAuthorizeError.
func (mr *MockOAuth2ProviderMockRecorder) WritePushedAuthorizeError(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WritePushedAuthorizeError", reflect.TypeOf((*MockOAuth2Provider)(nil).WritePushedAuthorizeError), arg0, arg1, arg2, arg3)
}
// WritePushedAuthorizeResponse mocks base method.
func (m *MockOAuth2Provider) WritePushedAuthorizeResponse(arg0 context.Context, arg1 http.ResponseWriter, arg2 fosite.AuthorizeRequester, arg3 fosite.PushedAuthorizeResponder) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "WritePushedAuthorizeResponse", arg0, arg1, arg2, arg3)
}
// WritePushedAuthorizeResponse indicates an expected call of WritePushedAuthorizeResponse.
func (mr *MockOAuth2ProviderMockRecorder) WritePushedAuthorizeResponse(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WritePushedAuthorizeResponse", reflect.TypeOf((*MockOAuth2Provider)(nil).WritePushedAuthorizeResponse), arg0, arg1, arg2, arg3)
}
// WriteRevocationResponse mocks base method.
func (m *MockOAuth2Provider) WriteRevocationResponse(arg0 context.Context, arg1 http.ResponseWriter, arg2 error) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "WriteRevocationResponse", arg0, arg1, arg2)
}
// WriteRevocationResponse indicates an expected call of WriteRevocationResponse.
func (mr *MockOAuth2ProviderMockRecorder) WriteRevocationResponse(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WriteRevocationResponse", reflect.TypeOf((*MockOAuth2Provider)(nil).WriteRevocationResponse), arg0, arg1, arg2)
} |
Go | hydra/oauth2/oauth2_refresh_token_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2_test
import (
"context"
"errors"
"fmt"
"math/rand"
"net/url"
"strings"
"sync"
"testing"
"time"
"github.com/gofrs/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/ory/fosite"
hc "github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/driver"
"github.com/ory/hydra/v2/internal"
"github.com/ory/hydra/v2/oauth2"
"github.com/ory/x/contextx"
"github.com/ory/x/dbal"
"github.com/ory/x/networkx"
)
// TestCreateRefreshTokenSessionStress is a sanity test to verify the fix for https://github.com/ory/hydra/issues/1719 &
// https://github.com/ory/hydra/issues/1735.
// It currently only deals with Postgres as that was what the issue was based on due to the default isolation level used
// by the storage engine.
func TestCreateRefreshTokenSessionStress(t *testing.T) {
if testing.Short() {
return
}
// number of iterations this test will make to ensure everything is working as expected. This test is aiming to
// prove correct behaviour when the handler is getting hit with the same refresh token in concurrent requests. Given
// that problems that may occur in this scenario are "racey" in nature, it is important to run this test several times
// so to minimize the probability were we pass due to sheer luck.
testRuns := 5
// number of workers that will concurrently hit the 'CreateRefreshTokenSession' method using the same refresh token.
// don't set this value to be too high as it will result in connection failures to the DB instance. The test is designed such that
// it will retry in the event we get unlucky and a transaction completes successfully prior to other requests getting past the
// first read.
workers := 10
token := "234c678fed33c1d2025537ae464a1ebf7d23fc4a" //nolint:gosec
tokenSignature := "4c7c7e8b3a77ad0c3ec846a21653c48b45dbfa31" //nolint:gosec
testClient := hc.Client{
ID: uuid.Must(uuid.NewV4()),
Secret: "secret",
ResponseTypes: []string{"id_token", "code", "token"},
GrantTypes: []string{"implicit", "refresh_token", "authorization_code", "password", "client_credentials"},
Scope: "hydra offline openid",
Audience: []string{"https://api.ory.sh/"},
}
request := &fosite.AccessRequest{
GrantTypes: []string{
"refresh_token",
},
Request: fosite.Request{
RequestedAt: time.Now(),
ID: uuid.Must(uuid.NewV4()).String(),
Client: &hc.Client{
ID: uuid.FromStringOrNil(testClient.GetID()),
},
RequestedScope: []string{"offline"},
GrantedScope: []string{"offline"},
Session: oauth2.NewSession(""),
Form: url.Values{
"refresh_token": []string{fmt.Sprintf("%s.%s", token, tokenSignature)},
},
},
}
setupRegistries(t)
for dbName, dbRegistry := range registries {
if dbName == "memory" {
// todo check why sqlite fails with "no such table: hydra_oauth2_refresh \n sqlite create"
// should be fine though as nobody should use sqlite in production
continue
}
net := &networkx.Network{}
require.NoError(t, dbRegistry.Persister().Connection(context.Background()).First(net))
dbRegistry.WithContextualizer(&contextx.Static{NID: net.ID, C: internal.NewConfigurationWithDefaults().Source(context.Background())})
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
t.Cleanup(cancel)
require.NoError(t, dbRegistry.OAuth2Storage().(clientCreator).CreateClient(ctx, &testClient))
require.NoError(t, dbRegistry.OAuth2Storage().CreateRefreshTokenSession(ctx, tokenSignature, request))
_, err := dbRegistry.OAuth2Storage().GetRefreshTokenSession(ctx, tokenSignature, nil)
require.NoError(t, err)
provider := dbRegistry.OAuth2Provider()
storageVersion := dbVersion(t, ctx, dbRegistry)
var wg sync.WaitGroup
for run := 0; run < testRuns; run++ {
barrier := make(chan struct{})
errorsCh := make(chan error, workers)
go func() {
for w := 0; w < workers; w++ {
wg.Add(1)
go func(run, worker int) {
defer wg.Done()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) //nolint:gosec
// all workers will block here until the for loop above has launched all the worker go-routines
// this is to ensure we fire all the workers off at the same
<-barrier
_, err := provider.NewAccessResponse(ctx, request)
errorsCh <- err
}(run, w)
}
// wait until all workers have completed their work
wg.Wait()
close(errorsCh)
}()
// let the race begin!
// all worker go-routines will now attempt to hit the "NewAccessResponse" method
close(barrier)
// process worker results
// successCount is the number of workers that were able to call "NewAccessResponse" without receiving an error.
// if the successCount at the end of a test run is bigger than one, it means that multiple access/refresh tokens
// were issued using the same refresh token! - https://knowyourmeme.com/memes/scared-hamster
var successCount int
for err := range errorsCh {
if err != nil {
if e := (&fosite.RFC6749Error{}); errors.As(err, &e) {
switch e.ErrorField {
// change logic below when the refresh handler starts returning 'fosite.ErrInvalidRequest' for other reasons.
// as of now, this error is only returned due to concurrent transactions competing to refresh using the same token.
case fosite.ErrInvalidRequest.ErrorField, fosite.ErrServerError.ErrorField:
// the error description copy is defined by RFC 6749 and should not be different regardless of
// the underlying transactional aware storage backend used by hydra
assert.Contains(t, []string{fosite.ErrInvalidRequest.DescriptionField, fosite.ErrServerError.DescriptionField}, e.DescriptionField)
// the database error debug copy will be different depending on the underlying database used
switch dbName {
case dbal.DriverMySQL:
case dbal.DriverPostgreSQL, dbal.DriverCockroachDB:
var matched bool
for _, errSubstr := range []string{
// both postgreSQL & cockroachDB return error code 40001 for consistency errors as a result of
// using the REPEATABLE_READ isolation level
"SQLSTATE 40001",
// possible if one worker starts the transaction AFTER another worker has successfully
// refreshed the token and committed the transaction
"not_found",
// postgres: duplicate key value violates unique constraint "hydra_oauth2_access_request_id_idx": Unable to insert or update resource because a resource with that value exists already: The request could not be completed due to concurrent access
"duplicate key",
// cockroach: restart transaction: TransactionRetryWithProtoRefreshError: TransactionRetryError: retry txn (RETRY_WRITE_TOO_OLD - WriteTooOld flag converted to WriteTooOldError): "sql txn" meta={id=7f069400 key=/Table/62/2/"02a55d6e-509b-4d7a-8458-5828b2f831a1"/0 pri=0.00598277 epo=0 ts=1600955431.566576173,2 min=1600955431.566576173,0 seq=6} lock=true stat=PENDING rts=1600955431.566576173,2 wto=false max=1600955431.566576173,0: Unable to serialize access due to a concurrent update in another session: The request could not be completed due to concurrent access
"RETRY_WRITE_TOO_OLD",
// postgres: pq: deadlock detected
"deadlock detected",
// postgres: pq: could not serialize access due to concurrent update: Unable to serialize access due to a concurrent update in another session: The request could not be completed due to concurrent access
"concurrent update",
// cockroach: this happens when there is an error with the storage
"RETRY_WRITE_TOO_OLD",
// refresh token reuse detection
"token_inactive",
} {
if strings.Contains(e.DebugField, errSubstr) {
matched = true
break
}
}
assert.True(t, matched, "received an unexpected kind of `%s`\n"+
"DB version: %s\n"+
"Error description: %s\n"+
"Error debug: %s\n"+
"Error hint: %s\n"+
"Raw error: %T %+v\n"+
"Raw cause: %T %+v",
e.ErrorField,
storageVersion,
e.DescriptionField,
e.DebugField,
e.HintField,
err, err,
e, e)
}
default:
// unfortunately, MySQL does not offer the same behaviour under the "REPEATABLE_READ" isolation
// level so we have to relax this assertion just for MySQL for the time being as server_errors
// resembling the following can be returned:
//
// Error 1213: Deadlock found when trying to get lock; try restarting transaction
if dbName != dbal.DriverMySQL {
t.Errorf("an unexpected RFC6749 error with the name %q was returned.\n"+
"Hint: has the refresh token error handling changed in fosite? If so, you need to add further "+
"assertions here to cover the additional errors that are being returned by the handler.\n"+
"DB version: %s\n"+
"Error description: %s\n"+
"Error debug: %s\n"+
"Error hint: %s\n"+
"Raw error: %+v",
e.ErrorField,
storageVersion,
e.DescriptionField,
e.DebugField,
e.HintField,
err)
}
}
} else {
t.Errorf("expected underlying error to be of type '*fosite.RFC6749Error', but it was "+
"actually of type %T: %+v - DB version: %s", err, err, storageVersion)
}
} else {
successCount++
}
}
// IMPORTANT - skip consistency check for MySQL :(
//
// different DBMS's provide different consistency guarantees when using the "REPEATABLE_READ" isolation level
// Currently, MySQL's implementation of "REPEATABLE_READ" makes it possible for multiple concurrent requests
// to successfully utilize the same refresh token. Therefore, we skip the assertion below.
//
// TODO: this needs to be addressed by making it possible to use different isolation levels for various authorization
// flows depending on the underlying hydra storage backend. For example, if using MySQL, hydra should force
// the transaction isolation level to be "Serializable" when a request to the token handler is received.
switch dbName {
case dbal.DriverMySQL:
case dbal.DriverPostgreSQL, dbal.DriverCockroachDB:
require.Equal(t, 1, successCount, "CRITICAL: in test iteration %d, %d out of %d workers "+
"were able to use the refresh token. Exactly ONE was expected to be have been successful.",
run,
successCount,
workers)
}
// reset state for the next test iteration
assert.NoError(t, dbRegistry.OAuth2Storage().DeleteRefreshTokenSession(ctx, tokenSignature))
assert.NoError(t, dbRegistry.OAuth2Storage().CreateRefreshTokenSession(ctx, tokenSignature, request))
}
}
}
type version struct {
Version string `db:"version"`
}
func dbVersion(t *testing.T, ctx context.Context, registry driver.Registry) string {
var v version
versionFunc := "version()"
c := registry.Persister().Connection(ctx)
if c.Dialect.Name() == "sqlite3" {
versionFunc = "sqlite_version()"
}
/* #nosec G201 - versionFunc is an enum */
require.NoError(t, registry.Persister().Connection(ctx).RawQuery(fmt.Sprintf("select %s as version", versionFunc)).First(&v))
return v.Version
} |
Go | hydra/oauth2/refresh_hook.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2
import (
"context"
"encoding/json"
"github.com/ory/hydra/v2/x"
"github.com/ory/x/errorsx"
"github.com/ory/fosite"
"github.com/ory/hydra/v2/driver/config"
)
// Requester is a token endpoint's request context.
//
// swagger:ignore
type Requester struct {
// ClientID is the identifier of the OAuth 2.0 client.
ClientID string `json:"client_id"`
// GrantedScopes is the list of scopes granted to the OAuth 2.0 client.
GrantedScopes []string `json:"granted_scopes"`
// GrantedAudience is the list of audiences granted to the OAuth 2.0 client.
GrantedAudience []string `json:"granted_audience"`
// GrantTypes is the requests grant types.
GrantTypes []string `json:"grant_types"`
}
// RefreshTokenHookRequest is the request body sent to the refresh token hook.
//
// swagger:ignore
type RefreshTokenHookRequest struct {
// Subject is the identifier of the authenticated end-user.
Subject string `json:"subject"`
// Session is the request's session..
Session *Session `json:"session"`
// Requester is a token endpoint's request context.
Requester Requester `json:"requester"`
// ClientID is the identifier of the OAuth 2.0 client.
ClientID string `json:"client_id"`
// GrantedScopes is the list of scopes granted to the OAuth 2.0 client.
GrantedScopes []string `json:"granted_scopes"`
// GrantedAudience is the list of audiences granted to the OAuth 2.0 client.
GrantedAudience []string `json:"granted_audience"`
}
// RefreshTokenHook is an AccessRequestHook called for `refresh_token` grant type.
func RefreshTokenHook(reg interface {
config.Provider
x.HTTPClientProvider
}) AccessRequestHook {
return func(ctx context.Context, requester fosite.AccessRequester) error {
hookURL := reg.Config().TokenRefreshHookURL(ctx)
if hookURL == nil {
return nil
}
if !requester.GetGrantTypes().ExactOne("refresh_token") {
return nil
}
session, ok := requester.GetSession().(*Session)
if !ok {
return nil
}
requesterInfo := Requester{
ClientID: requester.GetClient().GetID(),
GrantedScopes: requester.GetGrantedScopes(),
GrantedAudience: requester.GetGrantedAudience(),
GrantTypes: requester.GetGrantTypes(),
}
reqBody := RefreshTokenHookRequest{
Session: session,
Requester: requesterInfo,
Subject: session.GetSubject(),
ClientID: requester.GetClient().GetID(),
GrantedScopes: requester.GetGrantedScopes(),
GrantedAudience: requester.GetGrantedAudience(),
}
reqBodyBytes, err := json.Marshal(&reqBody)
if err != nil {
return errorsx.WithStack(
fosite.ErrServerError.
WithWrap(err).
WithDescription("An error occurred while encoding the token hook.").
WithDebugf("Unable to encode the token hook body: %s", err),
)
}
err = executeHookAndUpdateSession(ctx, reg, hookURL, reqBodyBytes, session)
if err != nil {
return err
}
return nil
}
} |
Go | hydra/oauth2/registry.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2
import (
"github.com/ory/fosite"
"github.com/ory/fosite/handler/openid"
"github.com/ory/hydra/v2/aead"
"github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/consent"
"github.com/ory/hydra/v2/jwk"
"github.com/ory/hydra/v2/oauth2/trust"
"github.com/ory/hydra/v2/x"
)
type InternalRegistry interface {
client.Registry
jwk.Registry
trust.Registry
x.RegistryWriter
x.RegistryLogger
consent.Registry
Registry
FlowCipher() *aead.XChaCha20Poly1305
}
type Registry interface {
OAuth2Storage() x.FositeStorer
OAuth2Provider() fosite.OAuth2Provider
AudienceStrategy() fosite.AudienceMatchingStrategy
AccessTokenJWTStrategy() jwk.JWTSigner
OpenIDConnectRequestValidator() *openid.OpenIDConnectRequestValidator
AccessRequestHooks() []AccessRequestHook
OAuth2ProviderConfig() fosite.Configurator
} |
Go | hydra/oauth2/revocator_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2_test
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gobuffalo/pop/v6"
"github.com/ory/x/httprouterx"
"github.com/ory/hydra/v2/persistence/sql"
"github.com/ory/x/contextx"
hydra "github.com/ory/hydra-client-go/v2"
"github.com/ory/hydra/v2/internal"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/ory/fosite"
"github.com/ory/hydra/v2/oauth2"
"github.com/ory/hydra/v2/x"
)
func createAccessTokenSession(subject, client string, token string, expiresAt time.Time, fs x.FositeStorer, scopes fosite.Arguments) {
createAccessTokenSessionPairwise(subject, client, token, expiresAt, fs, scopes, "")
}
func createAccessTokenSessionPairwise(subject, client string, token string, expiresAt time.Time, fs x.FositeStorer, scopes fosite.Arguments, obfuscated string) {
ar := fosite.NewAccessRequest(oauth2.NewSession(subject))
ar.GrantedScope = fosite.Arguments{"core"}
if scopes != nil {
ar.GrantedScope = scopes
}
ar.RequestedAt = time.Now().UTC().Round(time.Minute)
ar.Client = &fosite.DefaultClient{ID: client}
ar.Session.SetExpiresAt(fosite.AccessToken, expiresAt)
ar.Session.(*oauth2.Session).Extra = map[string]interface{}{"foo": "bar"}
if obfuscated != "" {
ar.Session.(*oauth2.Session).Claims.Subject = obfuscated
}
if err := fs.CreateAccessTokenSession(context.Background(), token, ar); err != nil {
panic(err)
}
}
func countAccessTokens(t *testing.T, c *pop.Connection) int {
n, err := c.Count(&sql.OAuth2RequestSQL{Table: "access"})
require.NoError(t, err)
return n
}
func TestRevoke(t *testing.T) {
conf := internal.NewConfigurationWithDefaults()
reg := internal.NewRegistryMemory(t, conf, &contextx.Default{})
internal.MustEnsureRegistryKeys(context.Background(), reg, x.OpenIDConnectKeyName)
internal.AddFositeExamples(reg)
tokens := Tokens(reg.OAuth2ProviderConfig(), 4)
now := time.Now().UTC().Round(time.Second)
handler := reg.OAuth2Handler()
router := x.NewRouterAdmin(conf.AdminURL)
handler.SetRoutes(router, &httprouterx.RouterPublic{Router: router.Router}, func(h http.Handler) http.Handler {
return h
})
server := httptest.NewServer(router)
defer server.Close()
createAccessTokenSession("alice", "my-client", tokens[0][0], now.Add(time.Hour), reg.OAuth2Storage(), nil)
createAccessTokenSession("siri", "my-client", tokens[1][0], now.Add(time.Hour), reg.OAuth2Storage(), nil)
createAccessTokenSession("siri", "my-client", tokens[2][0], now.Add(-time.Hour), reg.OAuth2Storage(), nil)
createAccessTokenSession("siri", "encoded:client", tokens[3][0], now.Add(-time.Hour), reg.OAuth2Storage(), nil)
require.Equal(t, 4, countAccessTokens(t, reg.Persister().Connection(context.Background())))
client := hydra.NewAPIClient(hydra.NewConfiguration())
client.GetConfig().Servers = hydra.ServerConfigurations{{URL: server.URL}}
for k, c := range []struct {
token string
assert func(*testing.T)
}{
{
token: "invalid",
assert: func(t *testing.T) {
assert.Equal(t, 4, countAccessTokens(t, reg.Persister().Connection(context.Background())))
},
},
{
token: tokens[3][1],
assert: func(t *testing.T) {
assert.Equal(t, 4, countAccessTokens(t, reg.Persister().Connection(context.Background())))
},
},
{
token: tokens[0][1],
assert: func(t *testing.T) {
t.Logf("Tried to delete: %s %s", tokens[0][0], tokens[0][1])
assert.Equal(t, 3, countAccessTokens(t, reg.Persister().Connection(context.Background())))
},
},
{
token: tokens[0][1],
},
{
token: tokens[2][1],
assert: func(t *testing.T) {
assert.Equal(t, 2, countAccessTokens(t, reg.Persister().Connection(context.Background())))
},
},
{
token: tokens[1][1],
assert: func(t *testing.T) {
assert.Equal(t, 1, countAccessTokens(t, reg.Persister().Connection(context.Background())))
},
},
} {
t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) {
_, err := client.OAuth2Api.RevokeOAuth2Token(
context.WithValue(
context.Background(),
hydra.ContextBasicAuth,
hydra.BasicAuth{UserName: "my-client", Password: "foobar"},
)).Token(c.token).Execute()
require.NoError(t, err)
if c.assert != nil {
c.assert(t)
}
})
}
} |
Go | hydra/oauth2/session.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2
import (
"context"
"encoding/json"
"time"
"github.com/pkg/errors"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"github.com/mohae/deepcopy"
"github.com/ory/fosite"
"github.com/ory/fosite/handler/openid"
"github.com/ory/fosite/token/jwt"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/flow"
"github.com/ory/x/logrusx"
"github.com/ory/x/stringslice"
)
// swagger:ignore
type Session struct {
*openid.DefaultSession `json:"id_token"`
Extra map[string]interface{} `json:"extra"`
KID string `json:"kid"`
ClientID string `json:"client_id"`
ConsentChallenge string `json:"consent_challenge"`
ExcludeNotBeforeClaim bool `json:"exclude_not_before_claim"`
AllowedTopLevelClaims []string `json:"allowed_top_level_claims"`
MirrorTopLevelClaims bool `json:"mirror_top_level_claims"`
Flow *flow.Flow `json:"-"`
}
func NewSession(subject string) *Session {
ctx := context.Background()
provider := config.MustNew(ctx, logrusx.New("", ""))
return NewSessionWithCustomClaims(ctx, provider, subject)
}
func NewSessionWithCustomClaims(ctx context.Context, p *config.DefaultProvider, subject string) *Session {
allowedTopLevelClaims := p.AllowedTopLevelClaims(ctx)
mirrorTopLevelClaims := p.MirrorTopLevelClaims(ctx)
return &Session{
DefaultSession: &openid.DefaultSession{
Claims: new(jwt.IDTokenClaims),
Headers: new(jwt.Headers),
Subject: subject,
},
Extra: map[string]interface{}{},
AllowedTopLevelClaims: allowedTopLevelClaims,
MirrorTopLevelClaims: mirrorTopLevelClaims,
}
}
func (s *Session) GetJWTClaims() jwt.JWTClaimsContainer {
//a slice of claims that are reserved and should not be overridden
var reservedClaims = []string{"iss", "sub", "aud", "exp", "nbf", "iat", "jti", "client_id", "scp", "ext"}
//remove any reserved claims from the custom claims
allowedClaimsFromConfigWithoutReserved := stringslice.Filter(s.AllowedTopLevelClaims, func(s string) bool {
return stringslice.Has(reservedClaims, s)
})
//our new extra map which will be added to the jwt
var topLevelExtraWithMirrorExt = map[string]interface{}{}
//setting every allowed claim top level in jwt with respective value
for _, allowedClaim := range allowedClaimsFromConfigWithoutReserved {
if cl, ok := s.Extra[allowedClaim]; ok {
topLevelExtraWithMirrorExt[allowedClaim] = cl
}
}
//for every other claim that was already reserved and for mirroring, add original extra under "ext"
if s.MirrorTopLevelClaims {
topLevelExtraWithMirrorExt["ext"] = s.Extra
}
claims := &jwt.JWTClaims{
Subject: s.Subject,
Issuer: s.DefaultSession.Claims.Issuer,
//set our custom extra map as claims.Extra
Extra: topLevelExtraWithMirrorExt,
ExpiresAt: s.GetExpiresAt(fosite.AccessToken),
IssuedAt: time.Now(),
// No need to set the audience because that's being done by fosite automatically.
// Audience: s.Audience,
// The JTI MUST NOT BE FIXED or refreshing tokens will yield the SAME token
// JTI: s.JTI,
// These are set by the DefaultJWTStrategy
// Scope: s.Scope,
// Setting these here will cause the token to have the same iat/nbf values always
// IssuedAt: s.DefaultSession.Claims.IssuedAt,
// NotBefore: s.DefaultSession.Claims.IssuedAt,
}
if !s.ExcludeNotBeforeClaim {
claims.NotBefore = claims.IssuedAt
}
if claims.Extra == nil {
claims.Extra = map[string]interface{}{}
}
claims.Extra["client_id"] = s.ClientID
return claims
}
func (s *Session) GetJWTHeader() *jwt.Headers {
return &jwt.Headers{
Extra: map[string]interface{}{"kid": s.KID},
}
}
func (s *Session) Clone() fosite.Session {
if s == nil {
return nil
}
return deepcopy.Copy(s).(fosite.Session)
}
var keyRewrites = map[string]string{
"Extra": "extra",
"KID": "kid",
"ClientID": "client_id",
"ConsentChallenge": "consent_challenge",
"ExcludeNotBeforeClaim": "exclude_not_before_claim",
"AllowedTopLevelClaims": "allowed_top_level_claims",
"idToken.Headers.Extra": "id_token.headers.extra",
"idToken.ExpiresAt": "id_token.expires_at",
"idToken.Username": "id_token.username",
"idToken.Subject": "id_token.subject",
"idToken.Claims.JTI": "id_token.id_token_claims.jti",
"idToken.Claims.Issuer": "id_token.id_token_claims.iss",
"idToken.Claims.Subject": "id_token.id_token_claims.sub",
"idToken.Claims.Audience": "id_token.id_token_claims.aud",
"idToken.Claims.Nonce": "id_token.id_token_claims.nonce",
"idToken.Claims.ExpiresAt": "id_token.id_token_claims.exp",
"idToken.Claims.IssuedAt": "id_token.id_token_claims.iat",
"idToken.Claims.RequestedAt": "id_token.id_token_claims.rat",
"idToken.Claims.AuthTime": "id_token.id_token_claims.auth_time",
"idToken.Claims.AccessTokenHash": "id_token.id_token_claims.at_hash",
"idToken.Claims.AuthenticationContextClassReference": "id_token.id_token_claims.acr",
"idToken.Claims.AuthenticationMethodsReferences": "id_token.id_token_claims.amr",
"idToken.Claims.CodeHash": "id_token.id_token_claims.c_hash",
"idToken.Claims.Extra": "id_token.id_token_claims.ext",
}
func (s *Session) UnmarshalJSON(original []byte) (err error) {
transformed := original
originalParsed := gjson.ParseBytes(original)
for oldKey, newKey := range keyRewrites {
if !originalParsed.Get(oldKey).Exists() {
continue
}
transformed, err = sjson.SetRawBytes(transformed, newKey, []byte(originalParsed.Get(oldKey).Raw))
if err != nil {
return errors.WithStack(err)
}
}
for orig := range keyRewrites {
transformed, err = sjson.DeleteBytes(transformed, orig)
if err != nil {
return errors.WithStack(err)
}
}
if originalParsed.Get("idToken").Exists() {
transformed, err = sjson.DeleteBytes(transformed, "idToken")
if err != nil {
return errors.WithStack(err)
}
}
type t Session
if err := json.Unmarshal(transformed, (*t)(s)); err != nil {
return errors.WithStack(err)
}
return nil
} |
Go | hydra/oauth2/session_custom_claims_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2_test
import (
"context"
"testing"
"github.com/ory/fosite/handler/openid"
"github.com/ory/fosite/token/jwt"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/internal"
"github.com/ory/hydra/v2/oauth2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func createSessionWithCustomClaims(ctx context.Context, p *config.DefaultProvider, extra map[string]interface{}) oauth2.Session {
allowedTopLevelClaims := p.AllowedTopLevelClaims(ctx)
mirrorTopLevelClaims := p.MirrorTopLevelClaims(ctx)
session := &oauth2.Session{
DefaultSession: &openid.DefaultSession{
Claims: &jwt.IDTokenClaims{
Subject: "alice",
Issuer: "hydra.localhost",
},
Headers: new(jwt.Headers),
Subject: "alice",
},
Extra: extra,
AllowedTopLevelClaims: allowedTopLevelClaims,
MirrorTopLevelClaims: mirrorTopLevelClaims,
}
return *session
}
func TestCustomClaimsInSession(t *testing.T) {
ctx := context.Background()
c := internal.NewConfigurationWithDefaults()
t.Run("no_custom_claims", func(t *testing.T) {
c.MustSet(ctx, config.KeyAllowedTopLevelClaims, []string{})
session := createSessionWithCustomClaims(ctx, c, nil)
claims := session.GetJWTClaims().ToMapClaims()
assert.EqualValues(t, "alice", claims["sub"])
assert.NotEqual(t, "another-alice", claims["sub"])
require.Contains(t, claims, "iss")
assert.EqualValues(t, "hydra.localhost", claims["iss"])
assert.Empty(t, claims["ext"])
})
t.Run("custom_claim_gets_mirrored", func(t *testing.T) {
c.MustSet(ctx, config.KeyAllowedTopLevelClaims, []string{"foo"})
extra := map[string]interface{}{"foo": "bar"}
session := createSessionWithCustomClaims(ctx, c, extra)
claims := session.GetJWTClaims().ToMapClaims()
assert.EqualValues(t, "alice", claims["sub"])
assert.NotEqual(t, "another-alice", claims["sub"])
require.Contains(t, claims, "iss")
assert.EqualValues(t, "hydra.localhost", claims["iss"])
require.Contains(t, claims, "foo")
assert.EqualValues(t, "bar", claims["foo"])
require.Contains(t, claims, "ext")
extClaims, ok := claims["ext"].(map[string]interface{})
require.True(t, ok)
require.Contains(t, extClaims, "foo")
assert.EqualValues(t, "bar", extClaims["foo"])
})
t.Run("only_non_reserved_claims_get_mirrored", func(t *testing.T) {
c.MustSet(ctx, config.KeyAllowedTopLevelClaims, []string{"foo", "iss", "sub"})
extra := map[string]interface{}{"foo": "bar", "iss": "hydra.remote", "sub": "another-alice"}
session := createSessionWithCustomClaims(ctx, c, extra)
claims := session.GetJWTClaims().ToMapClaims()
assert.EqualValues(t, "alice", claims["sub"])
assert.NotEqual(t, "another-alice", claims["sub"])
require.Contains(t, claims, "iss")
assert.EqualValues(t, "hydra.localhost", claims["iss"])
assert.NotEqual(t, "hydra.remote", claims["iss"])
require.Contains(t, claims, "foo")
assert.EqualValues(t, "bar", claims["foo"])
require.Contains(t, claims, "ext")
extClaims, ok := claims["ext"].(map[string]interface{})
require.True(t, ok)
require.Contains(t, extClaims, "foo")
assert.EqualValues(t, "bar", extClaims["foo"])
require.Contains(t, extClaims, "iss")
assert.EqualValues(t, "hydra.remote", extClaims["iss"])
require.Contains(t, extClaims, "sub")
assert.EqualValues(t, "another-alice", extClaims["sub"])
})
t.Run("no_custom_claims_in_config", func(t *testing.T) {
c.MustSet(ctx, config.KeyAllowedTopLevelClaims, []string{})
extra := map[string]interface{}{"foo": "bar", "iss": "hydra.remote", "sub": "another-alice"}
session := createSessionWithCustomClaims(ctx, c, extra)
claims := session.GetJWTClaims().ToMapClaims()
assert.EqualValues(t, "alice", claims["sub"])
assert.NotEqual(t, "another-alice", claims["sub"])
require.Contains(t, claims, "iss")
assert.EqualValues(t, "hydra.localhost", claims["iss"])
assert.NotContains(t, claims, "foo")
require.Contains(t, claims, "ext")
extClaims, ok := claims["ext"].(map[string]interface{})
require.True(t, ok)
require.Contains(t, extClaims, "foo")
assert.EqualValues(t, "bar", extClaims["foo"])
require.Contains(t, extClaims, "sub")
assert.EqualValues(t, "another-alice", extClaims["sub"])
require.Contains(t, extClaims, "iss")
assert.EqualValues(t, "hydra.remote", extClaims["iss"])
})
t.Run("more_config_claims_than_given", func(t *testing.T) {
c.MustSet(ctx, config.KeyAllowedTopLevelClaims, []string{"foo", "baz", "bar", "iss"})
extra := map[string]interface{}{"foo": "foo_value", "sub": "another-alice"}
session := createSessionWithCustomClaims(ctx, c, extra)
claims := session.GetJWTClaims().ToMapClaims()
assert.EqualValues(t, "alice", claims["sub"])
assert.NotEqual(t, "another-alice", claims["sub"])
require.Contains(t, claims, "iss")
assert.EqualValues(t, "hydra.localhost", claims["iss"])
assert.NotEqual(t, "hydra.remote", claims["iss"])
require.Contains(t, claims, "foo")
assert.EqualValues(t, "foo_value", claims["foo"])
require.Contains(t, claims, "ext")
extClaims, ok := claims["ext"].(map[string]interface{})
require.True(t, ok)
require.Contains(t, extClaims, "foo")
assert.EqualValues(t, "foo_value", extClaims["foo"])
require.Contains(t, extClaims, "sub")
assert.EqualValues(t, "another-alice", extClaims["sub"])
})
t.Run("less_config_claims_than_given", func(t *testing.T) {
c.MustSet(ctx, config.KeyAllowedTopLevelClaims, []string{"foo", "sub"})
extra := map[string]interface{}{"foo": "foo_value", "bar": "bar_value", "baz": "baz_value", "sub": "another-alice"}
session := createSessionWithCustomClaims(ctx, c, extra)
claims := session.GetJWTClaims().ToMapClaims()
assert.EqualValues(t, "alice", claims["sub"])
assert.NotEqual(t, "another-alice", claims["sub"])
require.Contains(t, claims, "iss")
assert.EqualValues(t, "hydra.localhost", claims["iss"])
require.Contains(t, claims, "foo")
assert.EqualValues(t, "foo_value", claims["foo"])
assert.NotContains(t, claims, "bar")
assert.NotContains(t, claims, "baz")
require.Contains(t, claims, "ext")
extClaims, ok := claims["ext"].(map[string]interface{})
require.True(t, ok)
require.Contains(t, extClaims, "foo")
assert.EqualValues(t, "foo_value", extClaims["foo"])
require.Contains(t, extClaims, "sub")
assert.EqualValues(t, "another-alice", extClaims["sub"])
})
t.Run("unused_config_claims", func(t *testing.T) {
c.MustSet(ctx, config.KeyAllowedTopLevelClaims, []string{"foo", "bar"})
extra := map[string]interface{}{"foo": "foo_value", "baz": "baz_value", "sub": "another-alice"}
session := createSessionWithCustomClaims(ctx, c, extra)
claims := session.GetJWTClaims().ToMapClaims()
assert.EqualValues(t, "alice", claims["sub"])
assert.NotEqual(t, "another-alice", claims["sub"])
require.Contains(t, claims, "iss")
assert.EqualValues(t, "hydra.localhost", claims["iss"])
require.Contains(t, claims, "foo")
assert.EqualValues(t, "foo_value", claims["foo"])
assert.NotContains(t, claims, "bar")
assert.NotContains(t, claims, "baz")
require.Contains(t, claims, "ext")
extClaims, ok := claims["ext"].(map[string]interface{})
require.True(t, ok)
require.Contains(t, extClaims, "foo")
assert.EqualValues(t, "foo_value", extClaims["foo"])
require.Contains(t, extClaims, "sub")
assert.EqualValues(t, "another-alice", extClaims["sub"])
})
t.Run("config_claims_contain_reserved_claims", func(t *testing.T) {
c.MustSet(ctx, config.KeyAllowedTopLevelClaims, []string{"iss", "sub"})
extra := map[string]interface{}{"iss": "hydra.remote", "sub": "another-alice"}
session := createSessionWithCustomClaims(ctx, c, extra)
claims := session.GetJWTClaims().ToMapClaims()
assert.EqualValues(t, "alice", claims["sub"])
assert.NotEqual(t, "another-alice", claims["sub"])
require.Contains(t, claims, "iss")
assert.EqualValues(t, "hydra.localhost", claims["iss"])
assert.NotEqualValues(t, "hydra.remote", claims["iss"])
require.Contains(t, claims, "ext")
extClaims, ok := claims["ext"].(map[string]interface{})
require.True(t, ok)
require.Contains(t, extClaims, "sub")
assert.EqualValues(t, "another-alice", extClaims["sub"])
require.Contains(t, extClaims, "iss")
assert.EqualValues(t, "hydra.remote", extClaims["iss"])
})
} |
Go | hydra/oauth2/session_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2
import (
"encoding/json"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/ory/fosite"
"github.com/ory/fosite/handler/openid"
"github.com/ory/fosite/token/jwt"
"github.com/ory/x/assertx"
"github.com/ory/x/snapshotx"
_ "embed"
)
//go:embed fixtures/v1.11.8-session.json
var v1118Session []byte
//go:embed fixtures/v1.11.9-session.json
var v1119Session []byte
func parseTime(t *testing.T, ts string) time.Time {
out, err := time.Parse(time.RFC3339Nano, ts)
require.NoError(t, err)
return out
}
func TestUnmarshalSession(t *testing.T) {
expect := &Session{
DefaultSession: &openid.DefaultSession{
Claims: &jwt.IDTokenClaims{
JTI: "",
Issuer: "http://127.0.0.1:4444/",
Subject: "[email protected]",
Audience: []string{"auth-code-client"},
Nonce: "mbxojlzlkefzmlecvrzfkmpm",
ExpiresAt: parseTime(t, "0001-01-01T00:00:00Z"),
IssuedAt: parseTime(t, "2022-08-25T09:21:04Z"),
RequestedAt: parseTime(t, "2022-08-25T09:20:54Z"),
AuthTime: parseTime(t, "2022-08-25T09:21:01Z"),
AccessTokenHash: "",
AuthenticationContextClassReference: "0",
AuthenticationMethodsReferences: []string{},
CodeHash: "",
Extra: map[string]interface{}{
"sid": "177e1f44-a1e9-415c-bfa3-8b62280b182d",
},
},
Headers: &jwt.Headers{Extra: map[string]interface{}{
"kid": "public:hydra.openid.id-token",
}},
ExpiresAt: map[fosite.TokenType]time.Time{
fosite.AccessToken: parseTime(t, "2022-08-25T09:26:05Z"),
fosite.AuthorizeCode: parseTime(t, "2022-08-25T09:23:04.432089764Z"),
fosite.RefreshToken: parseTime(t, "2022-08-26T09:21:05Z"),
},
Username: "",
Subject: "[email protected]",
},
Extra: map[string]interface{}{},
KID: "public:hydra.jwt.access-token",
ClientID: "auth-code-client",
ConsentChallenge: "2261efbd447044a1b2f76b05c6aca164",
ExcludeNotBeforeClaim: false,
AllowedTopLevelClaims: []string{
"persona_id",
"persona_krn",
"grantType",
"market",
"zone",
"login_session_id",
},
}
t.Run("v1.11.8", func(t *testing.T) {
var actual Session
require.NoError(t, json.Unmarshal(v1118Session, &actual))
assertx.EqualAsJSON(t, expect, &actual)
snapshotx.SnapshotTExcept(t, &actual, nil)
})
t.Run("v1.11.9", func(t *testing.T) {
var actual Session
require.NoError(t, json.Unmarshal(v1119Session, &actual))
assertx.EqualAsJSON(t, expect, &actual)
snapshotx.SnapshotTExcept(t, &actual, nil)
})
} |
Go | hydra/oauth2/token_hook.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/url"
"github.com/hashicorp/go-retryablehttp"
"github.com/ory/hydra/v2/flow"
"github.com/ory/hydra/v2/x"
"github.com/ory/fosite"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/x/errorsx"
)
// AccessRequestHook is called when an access token request is performed.
type AccessRequestHook func(ctx context.Context, requester fosite.AccessRequester) error
// Request is a token endpoint's request context.
//
// swagger:ignore
type Request struct {
// ClientID is the identifier of the OAuth 2.0 client.
ClientID string `json:"client_id"`
// GrantedScopes is the list of scopes granted to the OAuth 2.0 client.
GrantedScopes []string `json:"granted_scopes"`
// GrantedAudience is the list of audiences granted to the OAuth 2.0 client.
GrantedAudience []string `json:"granted_audience"`
// GrantTypes is the requests grant types.
GrantTypes []string `json:"grant_types"`
// Payload is the requests payload.
Payload map[string][]string `json:"payload"`
}
// TokenHookRequest is the request body sent to the token hook.
//
// swagger:ignore
type TokenHookRequest struct {
// Session is the request's session..
Session *Session `json:"session"`
// Requester is a token endpoint's request context.
Request Request `json:"request"`
}
// TokenHookResponse is the response body received from the token hook.
//
// swagger:ignore
type TokenHookResponse struct {
// Session is the session data returned by the hook.
Session flow.AcceptOAuth2ConsentRequestSession `json:"session"`
}
func executeHookAndUpdateSession(ctx context.Context, reg x.HTTPClientProvider, hookURL *url.URL, reqBodyBytes []byte, session *Session) error {
req, err := retryablehttp.NewRequestWithContext(ctx, http.MethodPost, hookURL.String(), bytes.NewReader(reqBodyBytes))
if err != nil {
return errorsx.WithStack(
fosite.ErrServerError.
WithWrap(err).
WithDescription("An error occurred while preparing the token hook.").
WithDebugf("Unable to prepare the HTTP Request: %s", err),
)
}
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
resp, err := reg.HTTPClient(ctx).Do(req)
if err != nil {
return errorsx.WithStack(
fosite.ErrServerError.
WithWrap(err).
WithDescription("An error occurred while executing the token hook.").
WithDebugf("Unable to execute HTTP Request: %s", err),
)
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK:
// Token permitted with new session data
case http.StatusNoContent:
// Token is permitted without overriding session data
return nil
case http.StatusForbidden:
return errorsx.WithStack(
fosite.ErrAccessDenied.
WithDescription("The token hook target responded with an error.").
WithDebugf("Token hook responded with HTTP status code: %s", resp.Status),
)
default:
return errorsx.WithStack(
fosite.ErrServerError.
WithDescription("The token hook target responded with an error.").
WithDebugf("Token hook responded with HTTP status code: %s", resp.Status),
)
}
var respBody TokenHookResponse
if err := json.NewDecoder(resp.Body).Decode(&respBody); err != nil {
return errorsx.WithStack(
fosite.ErrServerError.
WithWrap(err).
WithDescription("The token hook target responded with an error.").
WithDebugf("Response from token hook could not be decoded: %s", err),
)
}
// Overwrite existing session data (extra claims).
session.Extra = respBody.Session.AccessToken
idTokenClaims := session.IDTokenClaims()
idTokenClaims.Extra = respBody.Session.IDToken
return nil
}
// TokenHook is an AccessRequestHook called for all grant types.
func TokenHook(reg interface {
config.Provider
x.HTTPClientProvider
}) AccessRequestHook {
return func(ctx context.Context, requester fosite.AccessRequester) error {
hookURL := reg.Config().TokenHookURL(ctx)
if hookURL == nil {
return nil
}
session, ok := requester.GetSession().(*Session)
if !ok {
return nil
}
request := Request{
ClientID: requester.GetClient().GetID(),
GrantedScopes: requester.GetGrantedScopes(),
GrantedAudience: requester.GetGrantedAudience(),
GrantTypes: requester.GetGrantTypes(),
Payload: requester.Sanitize([]string{"assertion"}).GetRequestForm(),
}
reqBody := TokenHookRequest{
Session: session,
Request: request,
}
reqBodyBytes, err := json.Marshal(&reqBody)
if err != nil {
return errorsx.WithStack(
fosite.ErrServerError.
WithWrap(err).
WithDescription("An error occurred while encoding the token hook.").
WithDebugf("Unable to encode the token hook body: %s", err),
)
}
err = executeHookAndUpdateSession(ctx, reg, hookURL, reqBodyBytes, session)
if err != nil {
return err
}
return nil
}
} |
JSON | hydra/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured-hook=legacy.json | {
"subject": "foo",
"session": {
"id_token": {
"id_token_claims": {
"jti": "",
"iss": "http://localhost:4444/",
"sub": "foo",
"aud": [
"app-client"
],
"nonce": "",
"at_hash": "",
"acr": "1",
"amr": null,
"c_hash": "",
"ext": {
"sid": ""
}
},
"headers": {
"extra": {
}
},
"username": "",
"subject": "foo"
},
"extra": {},
"client_id": "app-client",
"consent_challenge": "",
"exclude_not_before_claim": false,
"allowed_top_level_claims": [],
"mirror_top_level_claims": true
},
"requester": {
"client_id": "app-client",
"granted_scopes": [
"offline",
"openid",
"hydra.*"
],
"granted_audience": [],
"grant_types": [
"refresh_token"
]
},
"client_id": "app-client",
"granted_scopes": [
"offline",
"openid",
"hydra.*"
],
"granted_audience": []
} |
JSON | hydra/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured-hook=new.json | {
"session": {
"id_token": {
"id_token_claims": {
"jti": "",
"iss": "http://localhost:4444/",
"sub": "foo",
"aud": [
"app-client"
],
"nonce": "",
"at_hash": "",
"acr": "1",
"amr": null,
"c_hash": "",
"ext": {
"hooked": "legacy"
}
},
"headers": {
"extra": {
}
},
"username": "",
"subject": "foo"
},
"extra": {
"hooked": "legacy"
},
"client_id": "app-client",
"consent_challenge": "",
"exclude_not_before_claim": false,
"allowed_top_level_claims": [],
"mirror_top_level_claims": true
},
"request": {
"client_id": "app-client",
"granted_scopes": [
"offline",
"openid",
"hydra.*"
],
"granted_audience": [],
"grant_types": [
"refresh_token"
],
"payload": {}
}
} |
JSON | hydra/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=2-description=should_pass_because_prompt=none_and_max_age_is_less_than_auth_time-should_call_refresh_token_hook_if_configured-hook=legacy.json | {
"subject": "foo",
"session": {
"id_token": {
"id_token_claims": {
"jti": "",
"iss": "http://localhost:4444/",
"sub": "foo",
"aud": [
"app-client"
],
"nonce": "",
"at_hash": "",
"acr": "1",
"amr": null,
"c_hash": "",
"ext": {
"sid": ""
}
},
"headers": {
"extra": {
}
},
"username": "",
"subject": "foo"
},
"extra": {},
"client_id": "app-client",
"consent_challenge": "",
"exclude_not_before_claim": false,
"allowed_top_level_claims": [],
"mirror_top_level_claims": true
},
"requester": {
"client_id": "app-client",
"granted_scopes": [
"offline",
"openid",
"hydra.*"
],
"granted_audience": [],
"grant_types": [
"refresh_token"
]
},
"client_id": "app-client",
"granted_scopes": [
"offline",
"openid",
"hydra.*"
],
"granted_audience": []
} |
JSON | hydra/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=2-description=should_pass_because_prompt=none_and_max_age_is_less_than_auth_time-should_call_refresh_token_hook_if_configured-hook=new.json | {
"session": {
"id_token": {
"id_token_claims": {
"jti": "",
"iss": "http://localhost:4444/",
"sub": "foo",
"aud": [
"app-client"
],
"nonce": "",
"at_hash": "",
"acr": "1",
"amr": null,
"c_hash": "",
"ext": {
"hooked": "legacy"
}
},
"headers": {
"extra": {
}
},
"username": "",
"subject": "foo"
},
"extra": {
"hooked": "legacy"
},
"client_id": "app-client",
"consent_challenge": "",
"exclude_not_before_claim": false,
"allowed_top_level_claims": [],
"mirror_top_level_claims": true
},
"request": {
"client_id": "app-client",
"granted_scopes": [
"offline",
"openid",
"hydra.*"
],
"granted_audience": [],
"grant_types": [
"refresh_token"
],
"payload": {}
}
} |
JSON | hydra/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured-hook=legacy.json | {
"subject": "foo",
"session": {
"id_token": {
"id_token_claims": {
"jti": "",
"iss": "http://localhost:4444/",
"sub": "foo",
"aud": [
"app-client"
],
"nonce": "",
"at_hash": "",
"acr": "1",
"amr": null,
"c_hash": "",
"ext": {
"sid": ""
}
},
"headers": {
"extra": {
}
},
"username": "",
"subject": "foo"
},
"extra": {},
"client_id": "app-client",
"consent_challenge": "",
"exclude_not_before_claim": false,
"allowed_top_level_claims": [],
"mirror_top_level_claims": true
},
"requester": {
"client_id": "app-client",
"granted_scopes": [
"offline",
"openid",
"hydra.*"
],
"granted_audience": [],
"grant_types": [
"refresh_token"
]
},
"client_id": "app-client",
"granted_scopes": [
"offline",
"openid",
"hydra.*"
],
"granted_audience": []
} |
JSON | hydra/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured-hook=new.json | {
"session": {
"id_token": {
"id_token_claims": {
"jti": "",
"iss": "http://localhost:4444/",
"sub": "foo",
"aud": [
"app-client"
],
"nonce": "",
"at_hash": "",
"acr": "1",
"amr": null,
"c_hash": "",
"ext": {
"hooked": "legacy"
}
},
"headers": {
"extra": {
}
},
"username": "",
"subject": "foo"
},
"extra": {
"hooked": "legacy"
},
"client_id": "app-client",
"consent_challenge": "",
"exclude_not_before_claim": false,
"allowed_top_level_claims": [],
"mirror_top_level_claims": true
},
"request": {
"client_id": "app-client",
"granted_scopes": [
"offline",
"openid",
"hydra.*"
],
"granted_audience": [],
"grant_types": [
"refresh_token"
],
"payload": {}
}
} |
JSON | hydra/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured-hook=legacy.json | {
"subject": "foo",
"session": {
"id_token": {
"id_token_claims": {
"jti": "",
"iss": "http://localhost:4444/",
"sub": "foo",
"aud": [
"app-client"
],
"nonce": "",
"at_hash": "",
"acr": "1",
"amr": null,
"c_hash": "",
"ext": {
"sid": ""
}
},
"headers": {
"extra": {
}
},
"username": "",
"subject": "foo"
},
"extra": {},
"client_id": "app-client",
"consent_challenge": "",
"exclude_not_before_claim": false,
"allowed_top_level_claims": [],
"mirror_top_level_claims": true
},
"requester": {
"client_id": "app-client",
"granted_scopes": [
"offline",
"openid",
"hydra.*"
],
"granted_audience": [],
"grant_types": [
"refresh_token"
]
},
"client_id": "app-client",
"granted_scopes": [
"offline",
"openid",
"hydra.*"
],
"granted_audience": []
} |
JSON | hydra/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured-hook=new.json | {
"session": {
"id_token": {
"id_token_claims": {
"jti": "",
"iss": "http://localhost:4444/",
"sub": "foo",
"aud": [
"app-client"
],
"nonce": "",
"at_hash": "",
"acr": "1",
"amr": null,
"c_hash": "",
"ext": {
"hooked": "legacy"
}
},
"headers": {
"extra": {
}
},
"username": "",
"subject": "foo"
},
"extra": {
"hooked": "legacy"
},
"client_id": "app-client",
"consent_challenge": "",
"exclude_not_before_claim": false,
"allowed_top_level_claims": [],
"mirror_top_level_claims": true
},
"request": {
"client_id": "app-client",
"granted_scopes": [
"offline",
"openid",
"hydra.*"
],
"granted_audience": [],
"grant_types": [
"refresh_token"
],
"payload": {}
}
} |
JSON | hydra/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=2-description=should_pass_because_prompt=none_and_max_age_is_less_than_auth_time-should_call_refresh_token_hook_if_configured-hook=new.json | {
"session": {
"id_token": {
"id_token_claims": {
"jti": "",
"iss": "http://localhost:4444/",
"sub": "foo",
"aud": [
"app-client"
],
"nonce": "",
"at_hash": "",
"acr": "1",
"amr": null,
"c_hash": "",
"ext": {
"hooked": "legacy"
}
},
"headers": {
"extra": {
}
},
"username": "",
"subject": "foo"
},
"extra": {
"hooked": "legacy"
},
"client_id": "app-client",
"consent_challenge": "",
"exclude_not_before_claim": false,
"allowed_top_level_claims": [],
"mirror_top_level_claims": true
},
"request": {
"client_id": "app-client",
"granted_scopes": [
"offline",
"openid",
"hydra.*"
],
"granted_audience": [],
"grant_types": [
"refresh_token"
],
"payload": {}
}
} |
JSON | hydra/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured-hook=legacy.json | {
"subject": "foo",
"session": {
"id_token": {
"id_token_claims": {
"jti": "",
"iss": "http://localhost:4444/",
"sub": "foo",
"aud": [
"app-client"
],
"nonce": "",
"at_hash": "",
"acr": "1",
"amr": null,
"c_hash": "",
"ext": {
"sid": ""
}
},
"headers": {
"extra": {
}
},
"username": "",
"subject": "foo"
},
"extra": {},
"client_id": "app-client",
"consent_challenge": "",
"exclude_not_before_claim": false,
"allowed_top_level_claims": [],
"mirror_top_level_claims": true
},
"requester": {
"client_id": "app-client",
"granted_scopes": [
"offline",
"openid",
"hydra.*"
],
"granted_audience": [],
"grant_types": [
"refresh_token"
]
},
"client_id": "app-client",
"granted_scopes": [
"offline",
"openid",
"hydra.*"
],
"granted_audience": []
} |
JSON | hydra/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured-hook=new.json | {
"session": {
"id_token": {
"id_token_claims": {
"jti": "",
"iss": "http://localhost:4444/",
"sub": "foo",
"aud": [
"app-client"
],
"nonce": "",
"at_hash": "",
"acr": "1",
"amr": null,
"c_hash": "",
"ext": {
"hooked": "legacy"
}
},
"headers": {
"extra": {
}
},
"username": "",
"subject": "foo"
},
"extra": {
"hooked": "legacy"
},
"client_id": "app-client",
"consent_challenge": "",
"exclude_not_before_claim": false,
"allowed_top_level_claims": [],
"mirror_top_level_claims": true
},
"request": {
"client_id": "app-client",
"granted_scopes": [
"offline",
"openid",
"hydra.*"
],
"granted_audience": [],
"grant_types": [
"refresh_token"
],
"payload": {}
}
} |
JSON | hydra/oauth2/.snapshots/TestHandlerWellKnown-hsm_enabled=false.json | {
"authorization_endpoint": "http://hydra.localhost/oauth2/auth",
"backchannel_logout_session_supported": true,
"backchannel_logout_supported": true,
"claims_parameter_supported": false,
"claims_supported": [
"sub"
],
"code_challenge_methods_supported": [
"plain",
"S256"
],
"credentials_endpoint_draft_00": "http://hydra.localhost/credentials",
"credentials_supported_draft_00": [
{
"cryptographic_binding_methods_supported": [
"jwk"
],
"cryptographic_suites_supported": [
"PS256",
"RS256",
"ES256",
"PS384",
"RS384",
"ES384",
"PS512",
"RS512",
"ES512",
"EdDSA"
],
"format": "jwt_vc_json",
"types": [
"VerifiableCredential",
"UserInfoCredential"
]
}
],
"end_session_endpoint": "http://hydra.localhost/oauth2/sessions/logout",
"frontchannel_logout_session_supported": true,
"frontchannel_logout_supported": true,
"grant_types_supported": [
"authorization_code",
"implicit",
"client_credentials",
"refresh_token"
],
"id_token_signed_response_alg": [
"RS256"
],
"id_token_signing_alg_values_supported": [
"RS256"
],
"issuer": "http://hydra.localhost",
"jwks_uri": "http://hydra.localhost/.well-known/jwks.json",
"registration_endpoint": "http://client-register/registration",
"request_object_signing_alg_values_supported": [
"none",
"RS256",
"ES256"
],
"request_parameter_supported": true,
"request_uri_parameter_supported": true,
"require_request_uri_registration": true,
"response_modes_supported": [
"query",
"fragment"
],
"response_types_supported": [
"code",
"code id_token",
"id_token",
"token id_token",
"token",
"token id_token code"
],
"revocation_endpoint": "http://hydra.localhost/oauth2/revoke",
"scopes_supported": [
"offline_access",
"offline",
"openid"
],
"subject_types_supported": [
"pairwise",
"public"
],
"token_endpoint": "http://hydra.localhost/oauth2/token",
"token_endpoint_auth_methods_supported": [
"client_secret_post",
"client_secret_basic",
"private_key_jwt",
"none"
],
"userinfo_endpoint": "/userinfo",
"userinfo_signed_response_alg": [
"RS256"
],
"userinfo_signing_alg_values_supported": [
"none",
"RS256"
]
} |
JSON | hydra/oauth2/.snapshots/TestHandlerWellKnown-hsm_enabled=true.json | {
"authorization_endpoint": "http://hydra.localhost/oauth2/auth",
"backchannel_logout_session_supported": true,
"backchannel_logout_supported": true,
"claims_parameter_supported": false,
"claims_supported": [
"sub"
],
"code_challenge_methods_supported": [
"plain",
"S256"
],
"credentials_endpoint_draft_00": "http://hydra.localhost/credentials",
"credentials_supported_draft_00": [
{
"cryptographic_binding_methods_supported": [
"jwk"
],
"cryptographic_suites_supported": [
"PS256",
"RS256",
"ES256",
"PS384",
"RS384",
"ES384",
"PS512",
"RS512",
"ES512",
"EdDSA"
],
"format": "jwt_vc_json",
"types": [
"VerifiableCredential",
"UserInfoCredential"
]
}
],
"end_session_endpoint": "http://hydra.localhost/oauth2/sessions/logout",
"frontchannel_logout_session_supported": true,
"frontchannel_logout_supported": true,
"grant_types_supported": [
"authorization_code",
"implicit",
"client_credentials",
"refresh_token"
],
"id_token_signed_response_alg": [
"RS256"
],
"id_token_signing_alg_values_supported": [
"RS256"
],
"issuer": "http://hydra.localhost",
"jwks_uri": "http://hydra.localhost/.well-known/jwks.json",
"registration_endpoint": "http://client-register/registration",
"request_object_signing_alg_values_supported": [
"none",
"RS256",
"ES256"
],
"request_parameter_supported": true,
"request_uri_parameter_supported": true,
"require_request_uri_registration": true,
"response_modes_supported": [
"query",
"fragment"
],
"response_types_supported": [
"code",
"code id_token",
"id_token",
"token id_token",
"token",
"token id_token code"
],
"revocation_endpoint": "http://hydra.localhost/oauth2/revoke",
"scopes_supported": [
"offline_access",
"offline",
"openid"
],
"subject_types_supported": [
"pairwise",
"public"
],
"token_endpoint": "http://hydra.localhost/oauth2/token",
"token_endpoint_auth_methods_supported": [
"client_secret_post",
"client_secret_basic",
"private_key_jwt",
"none"
],
"userinfo_endpoint": "/userinfo",
"userinfo_signed_response_alg": [
"RS256"
],
"userinfo_signing_alg_values_supported": [
"none",
"RS256"
]
} |
JSON | hydra/oauth2/.snapshots/TestUnmarshalSession-v1.11.8.json | {
"id_token": {
"id_token_claims": {
"jti": "",
"iss": "http://127.0.0.1:4444/",
"sub": "[email protected]",
"aud": [
"auth-code-client"
],
"nonce": "mbxojlzlkefzmlecvrzfkmpm",
"exp": "0001-01-01T00:00:00Z",
"iat": "2022-08-25T09:21:04Z",
"rat": "2022-08-25T09:20:54Z",
"auth_time": "2022-08-25T09:21:01Z",
"at_hash": "",
"acr": "0",
"amr": [],
"c_hash": "",
"ext": {
"sid": "177e1f44-a1e9-415c-bfa3-8b62280b182d"
}
},
"headers": {
"extra": {
"kid": "public:hydra.openid.id-token"
}
},
"expires_at": {
"access_token": "2022-08-25T09:26:05Z",
"authorize_code": "2022-08-25T09:23:04.432089764Z",
"refresh_token": "2022-08-26T09:21:05Z"
},
"username": "",
"subject": "[email protected]"
},
"extra": {},
"kid": "public:hydra.jwt.access-token",
"client_id": "auth-code-client",
"consent_challenge": "2261efbd447044a1b2f76b05c6aca164",
"exclude_not_before_claim": false,
"allowed_top_level_claims": [
"persona_id",
"persona_krn",
"grantType",
"market",
"zone",
"login_session_id"
],
"mirror_top_level_claims": false
} |
JSON | hydra/oauth2/.snapshots/TestUnmarshalSession-v1.11.9.json | {
"id_token": {
"id_token_claims": {
"jti": "",
"iss": "http://127.0.0.1:4444/",
"sub": "[email protected]",
"aud": [
"auth-code-client"
],
"nonce": "mbxojlzlkefzmlecvrzfkmpm",
"exp": "0001-01-01T00:00:00Z",
"iat": "2022-08-25T09:21:04Z",
"rat": "2022-08-25T09:20:54Z",
"auth_time": "2022-08-25T09:21:01Z",
"at_hash": "",
"acr": "0",
"amr": [],
"c_hash": "",
"ext": {
"sid": "177e1f44-a1e9-415c-bfa3-8b62280b182d"
}
},
"headers": {
"extra": {
"kid": "public:hydra.openid.id-token"
}
},
"expires_at": {
"access_token": "2022-08-25T09:26:05Z",
"authorize_code": "2022-08-25T09:23:04.432089764Z",
"refresh_token": "2022-08-26T09:21:05Z"
},
"username": "",
"subject": "[email protected]"
},
"extra": {},
"kid": "public:hydra.jwt.access-token",
"client_id": "auth-code-client",
"consent_challenge": "2261efbd447044a1b2f76b05c6aca164",
"exclude_not_before_claim": false,
"allowed_top_level_claims": [
"persona_id",
"persona_krn",
"grantType",
"market",
"zone",
"login_session_id"
],
"mirror_top_level_claims": false
} |
JSON | hydra/oauth2/fixtures/v1.11.8-session.json | {
"idToken": {
"Claims": {
"JTI": "",
"Issuer": "http://127.0.0.1:4444/",
"Subject": "[email protected]",
"Audience": ["auth-code-client"],
"Nonce": "mbxojlzlkefzmlecvrzfkmpm",
"ExpiresAt": "0001-01-01T00:00:00Z",
"IssuedAt": "2022-08-25T09:21:04Z",
"RequestedAt": "2022-08-25T09:20:54Z",
"AuthTime": "2022-08-25T09:21:01Z",
"AccessTokenHash": "",
"AuthenticationContextClassReference": "0",
"AuthenticationMethodsReferences": [],
"CodeHash": "",
"Extra": {
"sid": "177e1f44-a1e9-415c-bfa3-8b62280b182d"
}
},
"Headers": {
"Extra": {
"kid": "public:hydra.openid.id-token"
}
},
"ExpiresAt": {
"access_token": "2022-08-25T09:26:05Z",
"authorize_code": "2022-08-25T09:23:04.432089764Z",
"refresh_token": "2022-08-26T09:21:05Z"
},
"Username": "",
"Subject": "[email protected]"
},
"extra": {},
"KID": "public:hydra.jwt.access-token",
"ClientID": "auth-code-client",
"ConsentChallenge": "2261efbd447044a1b2f76b05c6aca164",
"ExcludeNotBeforeClaim": false,
"AllowedTopLevelClaims": [
"persona_id",
"persona_krn",
"grantType",
"market",
"zone",
"login_session_id"
]
} |
JSON | hydra/oauth2/fixtures/v1.11.9-session.json | {
"id_token": {
"id_token_claims": {
"jti": "",
"iss": "http://127.0.0.1:4444/",
"sub": "[email protected]",
"aud": ["auth-code-client"],
"nonce": "mbxojlzlkefzmlecvrzfkmpm",
"exp": "0001-01-01T00:00:00Z",
"iat": "2022-08-25T09:21:04Z",
"rat": "2022-08-25T09:20:54Z",
"auth_time": "2022-08-25T09:21:01Z",
"at_hash": "",
"acr": "0",
"amr": [],
"c_hash": "",
"ext": {
"sid": "177e1f44-a1e9-415c-bfa3-8b62280b182d"
}
},
"headers": {
"extra": {
"kid": "public:hydra.openid.id-token"
}
},
"expires_at": {
"access_token": "2022-08-25T09:26:05Z",
"authorize_code": "2022-08-25T09:23:04.432089764Z",
"refresh_token": "2022-08-26T09:21:05Z"
},
"username": "",
"subject": "[email protected]"
},
"extra": {},
"kid": "public:hydra.jwt.access-token",
"client_id": "auth-code-client",
"consent_challenge": "2261efbd447044a1b2f76b05c6aca164",
"exclude_not_before_claim": false,
"allowed_top_level_claims": [
"persona_id",
"persona_krn",
"grantType",
"market",
"zone",
"login_session_id"
]
} |
Go | hydra/oauth2/flowctx/cookies.go | // Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package flowctx
import "github.com/ory/hydra/v2/client"
type (
CookieSuffixer interface {
CookieSuffix() string
}
StaticSuffix string
clientID string
)
func (s StaticSuffix) CookieSuffix() string { return string(s) }
func (s clientID) GetID() string { return string(s) }
const (
flowCookie = "ory_hydra_flow"
loginSessionCookie = "ory_hydra_loginsession"
)
func FlowCookie(suffix CookieSuffixer) string {
return flowCookie + "_" + suffix.CookieSuffix()
}
func LoginSessionCookie(suffix CookieSuffixer) string {
return loginSessionCookie + "_" + suffix.CookieSuffix()
}
func SuffixForClient(c client.IDer) StaticSuffix {
return StaticSuffix(client.CookieSuffix(c))
}
func SuffixFromStatic(id string) StaticSuffix {
return SuffixForClient(clientID(id))
} |
Go | hydra/oauth2/flowctx/encoding.go | // Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package flowctx
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"net/http"
"github.com/pkg/errors"
"github.com/ory/fosite"
"github.com/ory/hydra/v2/aead"
"github.com/ory/hydra/v2/driver/config"
)
type (
data struct {
Purpose purpose `json:"p,omitempty"`
}
purpose int
CodecOption func(ad *data)
)
const (
loginChallenge purpose = iota
loginVerifier
consentChallenge
consentVerifier
)
func withPurpose(purpose purpose) CodecOption { return func(ad *data) { ad.Purpose = purpose } }
var (
AsLoginChallenge = withPurpose(loginChallenge)
AsLoginVerifier = withPurpose(loginVerifier)
AsConsentChallenge = withPurpose(consentChallenge)
AsConsentVerifier = withPurpose(consentVerifier)
)
func additionalDataFromOpts(opts ...CodecOption) []byte {
if len(opts) == 0 {
return nil
}
ad := &data{}
for _, o := range opts {
o(ad)
}
b, err := json.Marshal(ad)
if err != nil {
// Panic is OK here because the struct and the parameters are all known.
panic("failed to marshal additional data: " + errors.WithStack(err).Error())
}
return b
}
// Decode decodes the given string to a value.
func Decode[T any](ctx context.Context, cipher aead.Cipher, encoded string, opts ...CodecOption) (*T, error) {
plaintext, err := cipher.Decrypt(ctx, encoded, additionalDataFromOpts(opts...))
if err != nil {
return nil, err
}
rawBytes, err := gzip.NewReader(bytes.NewReader(plaintext))
if err != nil {
return nil, err
}
defer func() { _ = rawBytes.Close() }()
var val T
if err = json.NewDecoder(rawBytes).Decode(&val); err != nil {
return nil, err
}
return &val, nil
}
// Encode encodes the given value to a string.
func Encode(ctx context.Context, cipher aead.Cipher, val any, opts ...CodecOption) (s string, err error) {
// Steps:
// 1. Encode to JSON
// 2. GZIP
// 3. Encrypt with AEAD (AES-GCM) + Base64 URL-encode
var b bytes.Buffer
gz := gzip.NewWriter(&b)
if err = json.NewEncoder(gz).Encode(val); err != nil {
return "", err
}
if err = gz.Close(); err != nil {
return "", err
}
return cipher.Encrypt(ctx, b.Bytes(), additionalDataFromOpts(opts...))
}
// SetCookie encrypts the given value and sets it in a cookie.
func SetCookie(ctx context.Context, w http.ResponseWriter, reg interface {
FlowCipher() *aead.XChaCha20Poly1305
config.Provider
}, cookieName string, value any, opts ...CodecOption) error {
cipher := reg.FlowCipher()
cookie, err := Encode(ctx, cipher, value, opts...)
if err != nil {
return err
}
http.SetCookie(w, &http.Cookie{
Name: cookieName,
Value: cookie,
HttpOnly: true,
Domain: reg.Config().CookieDomain(ctx),
Secure: reg.Config().CookieSecure(ctx),
SameSite: reg.Config().CookieSameSiteMode(ctx),
})
return nil
}
// DeleteCookie deletes the flow cookie.
func DeleteCookie(ctx context.Context, w http.ResponseWriter, reg interface {
config.Provider
}, cookieName string) error {
http.SetCookie(w, &http.Cookie{
Name: cookieName,
Value: "",
MaxAge: -1,
HttpOnly: true,
Domain: reg.Config().CookieDomain(ctx),
Secure: reg.Config().CookieSecure(ctx),
SameSite: reg.Config().CookieSameSiteMode(ctx),
})
return nil
}
// FromCookie looks up the value stored in the cookie and decodes it.
func FromCookie[T any](ctx context.Context, r *http.Request, cipher aead.Cipher, cookieName string, opts ...CodecOption) (*T, error) {
cookie, err := r.Cookie(cookieName)
if err != nil {
return nil, errors.WithStack(fosite.ErrInvalidClient.WithHint("No cookie found for this request. Please initiate a new flow and retry."))
}
return Decode[T](ctx, cipher, cookie.Value, opts...)
} |
Go | hydra/oauth2/trust/doc.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
// Package trust implements jwt-bearer grant management capabilities
//
// JWT-Bearer Grant represents resource owner (RO) permission for client to act on behalf of the RO using jwt.
// Client uses jwt to request access token to act as RO.
package trust
import (
"time"
)
// OAuth2 JWT Bearer Grant Type Issuer Trust Relationships
//
// swagger:model trustedOAuth2JwtGrantIssuers
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type trustedOAuth2JwtGrantIssuers []trustedOAuth2JwtGrantIssuer
// OAuth2 JWT Bearer Grant Type Issuer Trust Relationship
//
// swagger:model trustedOAuth2JwtGrantIssuer
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type trustedOAuth2JwtGrantIssuer struct {
// example: 9edc811f-4e28-453c-9b46-4de65f00217f
ID string `json:"id"`
// The "issuer" identifies the principal that issued the JWT assertion (same as "iss" claim in JWT).
// example: https://jwt-idp.example.com
Issuer string `json:"issuer"`
// The "subject" identifies the principal that is the subject of the JWT.
// example: [email protected]
Subject string `json:"subject"`
// The "allow_any_subject" indicates that the issuer is allowed to have any principal as the subject of the JWT.
AllowAnySubject bool `json:"allow_any_subject"`
// The "scope" contains list of scope values (as described in Section 3.3 of OAuth 2.0 [RFC6749])
// example: ["openid", "offline"]
Scope []string `json:"scope"`
// The "public_key" contains information about public key issued by "issuer", that will be used to check JWT assertion signature.
PublicKey trustedOAuth2JwtGrantJsonWebKey `json:"public_key"`
// The "created_at" indicates, when grant was created.
CreatedAt time.Time `json:"created_at"`
// The "expires_at" indicates, when grant will expire, so we will reject assertion from "issuer" targeting "subject".
ExpiresAt time.Time `json:"expires_at"`
}
// OAuth2 JWT Bearer Grant Type Issuer Trusted JSON Web Key
//
// swagger:model trustedOAuth2JwtGrantJsonWebKey
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type trustedOAuth2JwtGrantJsonWebKey struct {
// The "set" is basically a name for a group(set) of keys. Will be the same as "issuer" in grant.
// example: https://jwt-idp.example.com
Set string `json:"set"`
// The "key_id" is key unique identifier (same as kid header in jws/jwt).
// example: 123e4567-e89b-12d3-a456-426655440000
KeyID string `json:"kid"`
} |
Go | hydra/oauth2/trust/error.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package trust
import (
"net/http"
"github.com/ory/fosite"
)
var ErrMissingRequiredParameter = &fosite.RFC6749Error{
DescriptionField: "One of the required parameters is missing. Check your request parameters.",
ErrorField: "missing_required_parameter",
CodeField: http.StatusBadRequest,
} |
Go | hydra/oauth2/trust/grant.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package trust
import (
"time"
)
type Grant struct {
ID string `json:"id"`
// Issuer identifies the principal that issued the JWT assertion (same as iss claim in jwt).
Issuer string `json:"issuer"`
// Subject identifies the principal that is the subject of the JWT.
Subject string `json:"subject"`
// AllowAnySubject indicates that the issuer is allowed to have any principal as the subject of the JWT.
AllowAnySubject bool `json:"allow_any_subject"`
// Scope contains list of scope values (as described in Section 3.3 of OAuth 2.0 [RFC6749])
Scope []string `json:"scope"`
// PublicKeys contains information about public key issued by Issuer, that will be used to check JWT assertion signature.
PublicKey PublicKey `json:"public_key"`
// CreatedAt indicates, when grant was created.
CreatedAt time.Time `json:"created_at"`
// ExpiresAt indicates, when grant will expire, so we will reject assertion from Issuer targeting Subject.
ExpiresAt time.Time `json:"expires_at"`
}
type PublicKey struct {
// Set is basically a name for a group(set) of keys. Will be the same as Issuer in grant.
Set string `json:"set"`
// KeyID is key unique identifier (same as kid header in jws/jwt).
KeyID string `json:"kid"`
} |
Go | hydra/oauth2/trust/handler.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package trust
import (
"encoding/json"
"net/http"
"time"
"github.com/ory/fosite"
"github.com/ory/x/pagination/tokenpagination"
"github.com/ory/hydra/v2/x"
"github.com/ory/x/httprouterx"
"github.com/google/uuid"
"github.com/julienschmidt/httprouter"
"github.com/ory/x/errorsx"
)
const (
grantJWTBearerPath = "/trust/grants/jwt-bearer/issuers" // #nosec G101
)
type Handler struct {
registry InternalRegistry
}
func NewHandler(r InternalRegistry) *Handler {
return &Handler{registry: r}
}
func (h *Handler) SetRoutes(admin *httprouterx.RouterAdmin) {
admin.GET(grantJWTBearerPath+"/:id", h.getTrustedOAuth2JwtGrantIssuer)
admin.GET(grantJWTBearerPath, h.adminListTrustedOAuth2JwtGrantIssuers)
admin.POST(grantJWTBearerPath, h.trustOAuth2JwtGrantIssuer)
admin.DELETE(grantJWTBearerPath+"/:id", h.deleteTrustedOAuth2JwtGrantIssuer)
}
// Trust OAuth2 JWT Bearer Grant Type Issuer Request Body
//
// swagger:model trustOAuth2JwtGrantIssuer
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type trustOAuth2JwtGrantIssuerBody struct {
// The "issuer" identifies the principal that issued the JWT assertion (same as "iss" claim in JWT).
//
// required: true
// example: https://jwt-idp.example.com
Issuer string `json:"issuer"`
// The "subject" identifies the principal that is the subject of the JWT.
//
// example: [email protected]
Subject string `json:"subject"`
// The "allow_any_subject" indicates that the issuer is allowed to have any principal as the subject of the JWT.
AllowAnySubject bool `json:"allow_any_subject"`
// The "scope" contains list of scope values (as described in Section 3.3 of OAuth 2.0 [RFC6749])
//
// required:true
// example: ["openid", "offline"]
Scope []string `json:"scope"`
// The "jwk" contains public key in JWK format issued by "issuer", that will be used to check JWT assertion signature.
//
// required:true
JWK x.JSONWebKey `json:"jwk"`
// The "expires_at" indicates, when grant will expire, so we will reject assertion from "issuer" targeting "subject".
//
// required:true
ExpiresAt time.Time `json:"expires_at"`
}
// Trust OAuth2 JWT Bearer Grant Type Issuer Request
//
// swagger:parameters trustOAuth2JwtGrantIssuer
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type trustOAuth2JwtGrantIssuer struct {
// in: body
Body trustOAuth2JwtGrantIssuerBody
}
// swagger:route POST /admin/trust/grants/jwt-bearer/issuers oAuth2 trustOAuth2JwtGrantIssuer
//
// # Trust OAuth2 JWT Bearer Grant Type Issuer
//
// Use this endpoint to establish a trust relationship for a JWT issuer
// to perform JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication
// and Authorization Grants [RFC7523](https://datatracker.ietf.org/doc/html/rfc7523).
//
// Consumes:
// - application/json
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Responses:
// 201: trustedOAuth2JwtGrantIssuer
// default: genericError
func (h *Handler) trustOAuth2JwtGrantIssuer(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var grantRequest createGrantRequest
if err := json.NewDecoder(r.Body).Decode(&grantRequest); err != nil {
h.registry.Writer().WriteError(w, r,
errorsx.WithStack(&fosite.RFC6749Error{
ErrorField: "error",
DescriptionField: err.Error(),
CodeField: http.StatusBadRequest,
}))
return
}
if err := h.registry.GrantValidator().Validate(grantRequest); err != nil {
h.registry.Writer().WriteError(w, r, err)
return
}
grant := Grant{
ID: uuid.New().String(),
Issuer: grantRequest.Issuer,
Subject: grantRequest.Subject,
AllowAnySubject: grantRequest.AllowAnySubject,
Scope: grantRequest.Scope,
PublicKey: PublicKey{
Set: grantRequest.Issuer, // group all keys by issuer, so set=issuer
KeyID: grantRequest.PublicKeyJWK.KeyID,
},
CreatedAt: time.Now().UTC().Round(time.Second),
ExpiresAt: grantRequest.ExpiresAt.UTC().Round(time.Second),
}
if err := h.registry.GrantManager().CreateGrant(r.Context(), grant, grantRequest.PublicKeyJWK); err != nil {
h.registry.Writer().WriteError(w, r, err)
return
}
h.registry.Writer().WriteCreated(w, r, grantJWTBearerPath+"/"+grant.ID, &grant)
}
// Get Trusted OAuth2 JWT Bearer Grant Type Issuer Request
//
// swagger:parameters getTrustedOAuth2JwtGrantIssuer
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type getTrustedOAuth2JwtGrantIssuer struct {
// The id of the desired grant
//
// in: path
// required: true
ID string `json:"id"`
}
// swagger:route GET /admin/trust/grants/jwt-bearer/issuers/{id} oAuth2 getTrustedOAuth2JwtGrantIssuer
//
// # Get Trusted OAuth2 JWT Bearer Grant Type Issuer
//
// Use this endpoint to get a trusted JWT Bearer Grant Type Issuer. The ID is the one returned when you
// created the trust relationship.
//
// Consumes:
// - application/json
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Responses:
// 200: trustedOAuth2JwtGrantIssuer
// default: genericError
func (h *Handler) getTrustedOAuth2JwtGrantIssuer(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
var id = ps.ByName("id")
grant, err := h.registry.GrantManager().GetConcreteGrant(r.Context(), id)
if err != nil {
h.registry.Writer().WriteError(w, r, err)
return
}
h.registry.Writer().Write(w, r, grant)
}
// Delete Trusted OAuth2 JWT Bearer Grant Type Issuer Request
//
// swagger:parameters deleteTrustedOAuth2JwtGrantIssuer
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type deleteTrustedOAuth2JwtGrantIssuer struct {
// The id of the desired grant
// in: path
// required: true
ID string `json:"id"`
}
// swagger:route DELETE /admin/trust/grants/jwt-bearer/issuers/{id} oAuth2 deleteTrustedOAuth2JwtGrantIssuer
//
// # Delete Trusted OAuth2 JWT Bearer Grant Type Issuer
//
// Use this endpoint to delete trusted JWT Bearer Grant Type Issuer. The ID is the one returned when you
// created the trust relationship.
//
// Once deleted, the associated issuer will no longer be able to perform the JSON Web Token (JWT) Profile
// for OAuth 2.0 Client Authentication and Authorization Grant.
//
// Consumes:
// - application/json
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Responses:
// 204: emptyResponse
// default: genericError
func (h *Handler) deleteTrustedOAuth2JwtGrantIssuer(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
var id = ps.ByName("id")
if err := h.registry.GrantManager().DeleteGrant(r.Context(), id); err != nil {
h.registry.Writer().WriteError(w, r, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// List Trusted OAuth2 JWT Bearer Grant Type Issuers Request
//
// swagger:parameters listTrustedOAuth2JwtGrantIssuers
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type listTrustedOAuth2JwtGrantIssuers struct {
// If optional "issuer" is supplied, only jwt-bearer grants with this issuer will be returned.
//
// in: query
// required: false
Issuer string `json:"issuer"`
tokenpagination.TokenPaginator
}
// swagger:route GET /admin/trust/grants/jwt-bearer/issuers oAuth2 listTrustedOAuth2JwtGrantIssuers
//
// # List Trusted OAuth2 JWT Bearer Grant Type Issuers
//
// Use this endpoint to list all trusted JWT Bearer Grant Type Issuers.
//
// Consumes:
// - application/json
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Responses:
// 200: trustedOAuth2JwtGrantIssuers
// default: genericError
func (h *Handler) adminListTrustedOAuth2JwtGrantIssuers(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
page, itemsPerPage := x.ParsePagination(r)
optionalIssuer := r.URL.Query().Get("issuer")
grants, err := h.registry.GrantManager().GetGrants(r.Context(), itemsPerPage, page*itemsPerPage, optionalIssuer)
if err != nil {
h.registry.Writer().WriteError(w, r, err)
return
}
n, err := h.registry.GrantManager().CountGrants(r.Context())
if err != nil {
h.registry.Writer().WriteError(w, r, err)
return
}
x.PaginationHeader(w, r.URL, int64(n), page, itemsPerPage)
if grants == nil {
grants = []Grant{}
}
h.registry.Writer().Write(w, r, grants)
} |
Go | hydra/oauth2/trust/handler_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package trust_test
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/go-jose/go-jose/v3"
"github.com/tidwall/gjson"
"github.com/ory/x/pointerx"
"github.com/stretchr/testify/assert"
"github.com/ory/hydra/v2/oauth2/trust"
"github.com/ory/x/contextx"
"github.com/google/uuid"
"github.com/stretchr/testify/suite"
"github.com/ory/hydra/v2/driver"
"github.com/ory/hydra/v2/jwk"
hydra "github.com/ory/hydra-client-go/v2"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/internal"
"github.com/ory/hydra/v2/x"
)
// Define the suite, and absorb the built-in basic suite
// functionality from testify - including a T() method which
// returns the current testing context.
type HandlerTestSuite struct {
suite.Suite
registry driver.Registry
server *httptest.Server
hydraClient *hydra.APIClient
publicKey *rsa.PublicKey
}
// Setup will run before the tests in the suite are run.
func (s *HandlerTestSuite) SetupSuite() {
conf := internal.NewConfigurationWithDefaults()
conf.MustSet(context.Background(), config.KeySubjectTypesSupported, []string{"public"})
conf.MustSet(context.Background(), config.KeyDefaultClientScope, []string{"foo", "bar"})
s.registry = internal.NewRegistryMemory(s.T(), conf, &contextx.Default{})
router := x.NewRouterAdmin(conf.AdminURL)
handler := trust.NewHandler(s.registry)
handler.SetRoutes(router)
jwkHandler := jwk.NewHandler(s.registry)
jwkHandler.SetRoutes(router, x.NewRouterPublic(), func(h http.Handler) http.Handler {
return h
})
s.server = httptest.NewServer(router)
c := hydra.NewAPIClient(hydra.NewConfiguration())
c.GetConfig().Servers = hydra.ServerConfigurations{{URL: s.server.URL}}
s.hydraClient = c
s.publicKey = s.generatePublicKey()
}
// Setup before each test.
func (s *HandlerTestSuite) SetupTest() {
}
// Will run after all the tests in the suite have been run.
func (s *HandlerTestSuite) TearDownSuite() {
}
// Will run after each test in the suite.
func (s *HandlerTestSuite) TearDownTest() {
internal.CleanAndMigrate(s.registry)(s.T())
}
// In order for 'go test' to run this suite, we need to create
// a normal test function and pass our suite to suite.Run.
func TestHandlerTestSuite(t *testing.T) {
suite.Run(t, new(HandlerTestSuite))
}
func (s *HandlerTestSuite) TestGrantCanBeCreatedAndFetched() {
createRequestParams := s.newCreateJwtBearerGrantParams(
"ory",
"[email protected]",
false,
[]string{"openid", "offline", "profile"},
time.Now().Add(time.Hour),
)
model := createRequestParams
ctx := context.Background()
createResult, _, err := s.hydraClient.OAuth2Api.TrustOAuth2JwtGrantIssuer(ctx).TrustOAuth2JwtGrantIssuer(createRequestParams).Execute()
s.Require().NoError(err, "no errors expected on grant creation")
s.NotEmpty(createResult.Id, " grant id expected to be non-empty")
s.Equal(model.Issuer, *createResult.Issuer, "issuer must match")
s.Equal(*model.Subject, *createResult.Subject, "subject must match")
s.Equal(model.Scope, createResult.Scope, "scopes must match")
s.Equal(model.Issuer, *createResult.PublicKey.Set, "public key set must match grant issuer")
s.Equal(model.Jwk.Kid, *createResult.PublicKey.Kid, "public key id must match")
s.Equal(model.ExpiresAt.Round(time.Second).UTC().String(), createResult.ExpiresAt.Round(time.Second).UTC().String(), "expiration date must match")
getResult, _, err := s.hydraClient.OAuth2Api.GetTrustedOAuth2JwtGrantIssuer(ctx, *createResult.Id).Execute()
s.Require().NoError(err, "no errors expected on grant fetching")
s.Equal(*createResult.Id, *getResult.Id, " grant id must match")
s.Equal(model.Issuer, *getResult.Issuer, "issuer must match")
s.Equal(*model.Subject, *getResult.Subject, "subject must match")
s.Equal(model.Scope, getResult.Scope, "scopes must match")
s.Equal(model.Issuer, *getResult.PublicKey.Set, "public key set must match grant issuer")
s.Equal(model.Jwk.Kid, *getResult.PublicKey.Kid, "public key id must match")
s.Equal(model.ExpiresAt.Round(time.Second).UTC().String(), getResult.ExpiresAt.Round(time.Second).UTC().String(), "expiration date must match")
}
func (s *HandlerTestSuite) TestGrantCanNotBeCreatedWithSameIssuerSubjectKey() {
createRequestParams := s.newCreateJwtBearerGrantParams(
"ory",
"[email protected]",
false,
[]string{"openid", "offline", "profile"},
time.Now().Add(time.Hour),
)
ctx := context.Background()
_, _, err := s.hydraClient.OAuth2Api.TrustOAuth2JwtGrantIssuer(ctx).TrustOAuth2JwtGrantIssuer(createRequestParams).Execute()
s.Require().NoError(err, "no errors expected on grant creation")
_, _, err = s.hydraClient.OAuth2Api.TrustOAuth2JwtGrantIssuer(ctx).TrustOAuth2JwtGrantIssuer(createRequestParams).Execute()
s.Require().Error(err, "expected error, because grant with same issuer+subject+kid exists")
kid := uuid.New().String()
createRequestParams.Jwk.Kid = kid
_, _, err = s.hydraClient.OAuth2Api.TrustOAuth2JwtGrantIssuer(ctx).TrustOAuth2JwtGrantIssuer(createRequestParams).Execute()
s.NoError(err, "no errors expected on grant creation, because kid is now different")
}
func (s *HandlerTestSuite) TestGrantCanNotBeCreatedWithSubjectAndAnySubject() {
createRequestParams := s.newCreateJwtBearerGrantParams(
"ory",
"[email protected]",
true,
[]string{"openid", "offline", "profile"},
time.Now().Add(time.Hour),
)
_, _, err := s.hydraClient.OAuth2Api.TrustOAuth2JwtGrantIssuer(context.Background()).TrustOAuth2JwtGrantIssuer(createRequestParams).Execute()
s.Require().Error(err, "expected error, because a grant with a subject and allow_any_subject cannot be created")
}
func (s *HandlerTestSuite) TestGrantCanNotBeCreatedWithUnknownJWK() {
createRequestParams := hydra.TrustOAuth2JwtGrantIssuer{
AllowAnySubject: pointerx.Ptr(true),
ExpiresAt: time.Now().Add(1 * time.Hour),
Issuer: "ory",
Jwk: hydra.JsonWebKey{
Alg: "unknown",
},
Scope: []string{"openid", "offline", "profile"},
}
_, res, err := s.hydraClient.OAuth2Api.TrustOAuth2JwtGrantIssuer(context.Background()).TrustOAuth2JwtGrantIssuer(createRequestParams).Execute()
s.Assert().Equal(http.StatusBadRequest, res.StatusCode)
body, _ := io.ReadAll(res.Body)
s.Contains(gjson.GetBytes(body, "error_description").String(), "unknown json web key type")
s.Require().Error(err, "expected error, because the key type was unknown")
}
func (s *HandlerTestSuite) TestGrantCanNotBeCreatedWithMissingFields() {
createRequestParams := s.newCreateJwtBearerGrantParams(
"",
"[email protected]",
false,
[]string{"openid", "offline", "profile"},
time.Now().Add(time.Hour),
)
_, _, err := s.hydraClient.OAuth2Api.TrustOAuth2JwtGrantIssuer(context.Background()).TrustOAuth2JwtGrantIssuer(createRequestParams).Execute()
s.Require().Error(err, "expected error, because grant missing issuer")
createRequestParams = s.newCreateJwtBearerGrantParams(
"ory",
"",
false,
[]string{"openid", "offline", "profile"},
time.Now().Add(time.Hour),
)
_, _, err = s.hydraClient.OAuth2Api.TrustOAuth2JwtGrantIssuer(context.Background()).TrustOAuth2JwtGrantIssuer(createRequestParams).Execute()
s.Require().Error(err, "expected error, because grant missing subject")
createRequestParams = s.newCreateJwtBearerGrantParams(
"ory",
"[email protected]",
false,
[]string{"openid", "offline", "profile"},
time.Time{},
)
_, _, err = s.hydraClient.OAuth2Api.TrustOAuth2JwtGrantIssuer(context.Background()).TrustOAuth2JwtGrantIssuer(createRequestParams).Execute()
s.Error(err, "expected error, because grant missing expiration date")
}
func (s *HandlerTestSuite) TestGrantPublicCanBeFetched() {
createRequestParams := s.newCreateJwtBearerGrantParams(
"ory",
"[email protected]",
false,
[]string{"openid", "offline", "profile"},
time.Now().Add(time.Hour),
)
_, _, err := s.hydraClient.OAuth2Api.TrustOAuth2JwtGrantIssuer(context.Background()).TrustOAuth2JwtGrantIssuer(createRequestParams).Execute()
s.Require().NoError(err, "no error expected on grant creation")
getResult, _, err := s.hydraClient.JwkApi.GetJsonWebKey(context.Background(), createRequestParams.Issuer, createRequestParams.Jwk.Kid).Execute()
s.Require().NoError(err, "no error expected on fetching public key")
s.Equal(createRequestParams.Jwk.Kid, getResult.Keys[0].Kid)
}
func (s *HandlerTestSuite) TestGrantWithAnySubjectCanBeCreated() {
createRequestParams := s.newCreateJwtBearerGrantParams(
"ory",
"",
true,
[]string{"openid", "offline", "profile"},
time.Now().Add(time.Hour),
)
grant, _, err := s.hydraClient.OAuth2Api.TrustOAuth2JwtGrantIssuer(context.Background()).TrustOAuth2JwtGrantIssuer(createRequestParams).Execute()
s.Require().NoError(err, "no error expected on grant creation")
assert.Empty(s.T(), grant.Subject)
assert.Truef(s.T(), *grant.AllowAnySubject, "grant with any subject must be true")
}
func (s *HandlerTestSuite) TestGrantListCanBeFetched() {
createRequestParams := s.newCreateJwtBearerGrantParams(
"ory",
"[email protected]",
false,
[]string{"openid", "offline", "profile"},
time.Now().Add(time.Hour),
)
createRequestParams2 := s.newCreateJwtBearerGrantParams(
"ory2",
"[email protected]",
false,
[]string{"profile"},
time.Now().Add(time.Hour),
)
_, _, err := s.hydraClient.OAuth2Api.TrustOAuth2JwtGrantIssuer(context.Background()).TrustOAuth2JwtGrantIssuer(createRequestParams).Execute()
s.Require().NoError(err, "no errors expected on grant creation")
_, _, err = s.hydraClient.OAuth2Api.TrustOAuth2JwtGrantIssuer(context.Background()).TrustOAuth2JwtGrantIssuer(createRequestParams2).Execute()
s.Require().NoError(err, "no errors expected on grant creation")
getResult, _, err := s.hydraClient.OAuth2Api.ListTrustedOAuth2JwtGrantIssuers(context.Background()).Execute()
s.Require().NoError(err, "no errors expected on grant list fetching")
s.Len(getResult, 2, "expected to get list of 2 grants")
getResult, _, err = s.hydraClient.OAuth2Api.ListTrustedOAuth2JwtGrantIssuers(context.Background()).Issuer(createRequestParams2.Issuer).Execute()
s.Require().NoError(err, "no errors expected on grant list fetching")
s.Len(getResult, 1, "expected to get list of 1 grant, when filtering by issuer")
s.Equal(createRequestParams2.Issuer, *getResult[0].Issuer, "issuer must match")
}
func (s *HandlerTestSuite) TestGrantCanBeDeleted() {
createRequestParams := s.newCreateJwtBearerGrantParams(
"ory",
"[email protected]",
false,
[]string{"openid", "offline", "profile"},
time.Now().Add(time.Hour),
)
createResult, _, err := s.hydraClient.OAuth2Api.TrustOAuth2JwtGrantIssuer(context.Background()).TrustOAuth2JwtGrantIssuer(createRequestParams).Execute()
s.Require().NoError(err, "no errors expected on grant creation")
_, err = s.hydraClient.OAuth2Api.DeleteTrustedOAuth2JwtGrantIssuer(context.Background(), *createResult.Id).Execute()
s.Require().NoError(err, "no errors expected on grant deletion")
_, err = s.hydraClient.OAuth2Api.DeleteTrustedOAuth2JwtGrantIssuer(context.Background(), *createResult.Id).Execute()
s.Error(err, "expected error, because grant has been already deleted")
}
func (s *HandlerTestSuite) generateJWK(publicKey *rsa.PublicKey) hydra.JsonWebKey {
var b bytes.Buffer
s.Require().NoError(json.NewEncoder(&b).Encode(&jose.JSONWebKey{
Key: publicKey,
KeyID: uuid.New().String(),
Algorithm: string(jose.RS256),
Use: "sig",
}))
var mJWK hydra.JsonWebKey
s.Require().NoError(json.NewDecoder(&b).Decode(&mJWK))
return mJWK
}
func (s *HandlerTestSuite) newCreateJwtBearerGrantParams(
issuer, subject string, allowAnySubject bool, scope []string, expiresAt time.Time,
) hydra.TrustOAuth2JwtGrantIssuer {
return hydra.TrustOAuth2JwtGrantIssuer{
ExpiresAt: expiresAt,
Issuer: issuer,
Jwk: s.generateJWK(s.publicKey),
Scope: scope,
Subject: pointerx.String(subject),
AllowAnySubject: pointerx.Bool(allowAnySubject),
}
}
func (s *HandlerTestSuite) generatePublicKey() *rsa.PublicKey {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
s.Require().NoError(err)
return &privateKey.PublicKey
} |
Go | hydra/oauth2/trust/manager.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package trust
import (
"context"
"time"
"github.com/go-jose/go-jose/v3"
"github.com/gofrs/uuid"
)
type GrantManager interface {
CreateGrant(ctx context.Context, g Grant, publicKey jose.JSONWebKey) error
GetConcreteGrant(ctx context.Context, id string) (Grant, error)
DeleteGrant(ctx context.Context, id string) error
GetGrants(ctx context.Context, limit, offset int, optionalIssuer string) ([]Grant, error)
CountGrants(ctx context.Context) (int, error)
FlushInactiveGrants(ctx context.Context, notAfter time.Time, limit int, batchSize int) error
}
type SQLData struct {
ID string `db:"id"`
NID uuid.UUID `db:"nid"`
Issuer string `db:"issuer"`
Subject string `db:"subject"`
AllowAnySubject bool `db:"allow_any_subject"`
Scope string `db:"scope"`
KeySet string `db:"key_set"`
KeyID string `db:"key_id"`
CreatedAt time.Time `db:"created_at"`
ExpiresAt time.Time `db:"expires_at"`
}
func (SQLData) TableName() string {
return "hydra_oauth2_trusted_jwt_bearer_issuer"
} |
Go | hydra/oauth2/trust/manager_test_helpers.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package trust
import (
"context"
"sort"
"testing"
"time"
"github.com/ory/x/josex"
"github.com/go-jose/go-jose/v3"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/ory/hydra/v2/jwk"
)
func TestHelperGrantManagerCreateGetDeleteGrant(t1 GrantManager, km jwk.Manager, parallel bool) func(t *testing.T) {
tokenServicePubKey1 := jose.JSONWebKey{}
tokenServicePubKey2 := jose.JSONWebKey{}
mikePubKey := jose.JSONWebKey{}
return func(t *testing.T) {
if parallel {
t.Parallel()
}
kid1, kid2 := uuid.NewString(), uuid.NewString()
kid3 := uuid.NewString()
set := uuid.NewString()
keySet, err := km.GenerateAndPersistKeySet(context.Background(), set, kid1, string(jose.RS256), "sig")
require.NoError(t, err)
tokenServicePubKey1 = josex.ToPublicKey(&keySet.Keys[0])
keySet, err = km.GenerateAndPersistKeySet(context.Background(), set, kid2, string(jose.RS256), "sig")
require.NoError(t, err)
tokenServicePubKey2 = josex.ToPublicKey(&keySet.Keys[0])
keySet, err = km.GenerateAndPersistKeySet(context.Background(), "https://mike.example.com", kid3, string(jose.RS256), "sig")
require.NoError(t, err)
mikePubKey = josex.ToPublicKey(&keySet.Keys[0])
storedGrants, err := t1.GetGrants(context.TODO(), 100, 0, "")
require.NoError(t, err)
assert.Len(t, storedGrants, 0)
count, err := t1.CountGrants(context.TODO())
require.NoError(t, err)
assert.Equal(t, 0, count)
createdAt := time.Now().UTC().Round(time.Second)
expiresAt := createdAt.AddDate(1, 0, 0)
grant := Grant{
ID: uuid.New().String(),
Issuer: set,
Subject: "[email protected]",
Scope: []string{"openid", "offline"},
PublicKey: PublicKey{
Set: set,
KeyID: kid1,
},
CreatedAt: createdAt,
ExpiresAt: expiresAt,
}
err = t1.CreateGrant(context.TODO(), grant, tokenServicePubKey1)
require.NoError(t, err)
storedGrant, err := t1.GetConcreteGrant(context.TODO(), grant.ID)
require.NoError(t, err)
assert.Equal(t, grant.ID, storedGrant.ID)
assert.Equal(t, grant.Issuer, storedGrant.Issuer)
assert.Equal(t, grant.Subject, storedGrant.Subject)
assert.Equal(t, grant.Scope, storedGrant.Scope)
assert.Equal(t, grant.PublicKey, storedGrant.PublicKey)
assert.Equal(t, grant.CreatedAt.Format(time.RFC3339), storedGrant.CreatedAt.Format(time.RFC3339))
assert.Equal(t, grant.ExpiresAt.Format(time.RFC3339), storedGrant.ExpiresAt.Format(time.RFC3339))
grant2 := Grant{
ID: uuid.New().String(),
Issuer: set,
Subject: "[email protected]",
Scope: []string{"openid"},
PublicKey: PublicKey{
Set: set,
KeyID: kid2,
},
CreatedAt: createdAt.Add(time.Minute * 5),
ExpiresAt: createdAt.Add(-time.Minute * 5),
}
err = t1.CreateGrant(context.TODO(), grant2, tokenServicePubKey2)
require.NoError(t, err)
grant3 := Grant{
ID: uuid.New().String(),
Issuer: "https://mike.example.com",
Subject: "[email protected]",
Scope: []string{"permissions", "openid", "offline"},
PublicKey: PublicKey{
Set: "https://mike.example.com",
KeyID: kid3,
},
CreatedAt: createdAt.Add(time.Hour),
ExpiresAt: createdAt.Add(-time.Hour * 24),
}
err = t1.CreateGrant(context.TODO(), grant3, mikePubKey)
require.NoError(t, err)
count, err = t1.CountGrants(context.TODO())
require.NoError(t, err)
assert.Equal(t, 3, count)
storedGrants, err = t1.GetGrants(context.TODO(), 100, 0, "")
sort.Slice(storedGrants, func(i, j int) bool {
return storedGrants[i].CreatedAt.Before(storedGrants[j].CreatedAt)
})
require.NoError(t, err)
require.Len(t, storedGrants, 3)
assert.Equal(t, grant.ID, storedGrants[0].ID)
assert.Equal(t, grant2.ID, storedGrants[1].ID)
assert.Equal(t, grant3.ID, storedGrants[2].ID)
storedGrants, err = t1.GetGrants(context.TODO(), 100, 0, set)
sort.Slice(storedGrants, func(i, j int) bool {
return storedGrants[i].CreatedAt.Before(storedGrants[j].CreatedAt)
})
require.NoError(t, err)
require.Len(t, storedGrants, 2)
assert.Equal(t, grant.ID, storedGrants[0].ID)
assert.Equal(t, grant2.ID, storedGrants[1].ID)
err = t1.DeleteGrant(context.TODO(), grant.ID)
require.NoError(t, err)
_, err = t1.GetConcreteGrant(context.TODO(), grant.ID)
require.Error(t, err)
count, err = t1.CountGrants(context.TODO())
require.NoError(t, err)
assert.Equal(t, 2, count)
err = t1.FlushInactiveGrants(context.TODO(), grant2.ExpiresAt, 1000, 100)
require.NoError(t, err)
count, err = t1.CountGrants(context.TODO())
require.NoError(t, err)
assert.Equal(t, 1, count)
_, err = t1.GetConcreteGrant(context.TODO(), grant2.ID)
assert.NoError(t, err)
}
}
func TestHelperGrantManagerErrors(m GrantManager, km jwk.Manager, parallel bool) func(t *testing.T) {
pubKey1 := jose.JSONWebKey{}
pubKey2 := jose.JSONWebKey{}
return func(t *testing.T) {
set := uuid.NewString()
kid1, kid2 := uuid.NewString(), uuid.NewString()
t.Parallel()
keySet, err := km.GenerateAndPersistKeySet(context.Background(), set, kid1, string(jose.RS256), "sig")
require.NoError(t, err)
pubKey1 = josex.ToPublicKey(&keySet.Keys[0])
keySet, err = km.GenerateAndPersistKeySet(context.Background(), set, kid2, string(jose.RS256), "sig")
require.NoError(t, err)
pubKey2 = josex.ToPublicKey(&keySet.Keys[0])
createdAt := time.Now()
expiresAt := createdAt.AddDate(1, 0, 0)
grant := Grant{
ID: uuid.New().String(),
Issuer: "issuer",
Subject: "subject",
Scope: []string{"openid", "offline"},
PublicKey: PublicKey{
Set: set,
KeyID: kid1,
},
CreatedAt: createdAt,
ExpiresAt: expiresAt,
}
err = m.CreateGrant(context.TODO(), grant, pubKey1)
require.NoError(t, err)
grant.ID = uuid.New().String()
err = m.CreateGrant(context.TODO(), grant, pubKey1)
require.Error(t, err, "error expected, because combination of issuer + subject + key_id must be unique")
grant2 := grant
grant2.PublicKey = PublicKey{
Set: set,
KeyID: kid2,
}
err = m.CreateGrant(context.TODO(), grant2, pubKey2)
require.NoError(t, err)
nonExistingGrantID := uuid.New().String()
err = m.DeleteGrant(context.TODO(), nonExistingGrantID)
require.Error(t, err, "expect error, when deleting non-existing grant")
_, err = m.GetConcreteGrant(context.TODO(), nonExistingGrantID)
require.Error(t, err, "expect error, when fetching non-existing grant")
}
} |
Go | hydra/oauth2/trust/registry.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package trust
import (
"github.com/ory/hydra/v2/x"
)
type InternalRegistry interface {
x.RegistryWriter
x.RegistryLogger
Registry
}
type Registry interface {
GrantManager() GrantManager
GrantValidator() *GrantValidator
} |
Go | hydra/oauth2/trust/request.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package trust
import (
"time"
"github.com/go-jose/go-jose/v3"
)
type createGrantRequest struct {
// Issuer identifies the principal that issued the JWT assertion (same as iss claim in jwt).
Issuer string `json:"issuer"`
// Subject identifies the principal that is the subject of the JWT.
Subject string `json:"subject"`
// AllowAnySubject indicates that the issuer is allowed to have any principal as the subject of the JWT.
AllowAnySubject bool `json:"allow_any_subject"`
// Scope contains list of scope values (as described in Section 3.3 of OAuth 2.0 [RFC6749])
Scope []string `json:"scope"`
// PublicKeyJWK contains public key in JWK format issued by Issuer, that will be used to check JWT assertion signature.
PublicKeyJWK jose.JSONWebKey `json:"jwk"`
// ExpiresAt indicates, when grant will expire, so we will reject assertion from Issuer targeting Subject.
ExpiresAt time.Time `json:"expires_at"`
} |
Go | hydra/oauth2/trust/validator.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package trust
import (
"github.com/ory/x/errorsx"
)
type GrantValidator struct {
}
func NewGrantValidator() *GrantValidator {
return &GrantValidator{}
}
func (v *GrantValidator) Validate(request createGrantRequest) error {
if request.Issuer == "" {
return errorsx.WithStack(ErrMissingRequiredParameter.WithHint("Field 'issuer' is required."))
}
if request.Subject == "" && !request.AllowAnySubject {
return errorsx.WithStack(ErrMissingRequiredParameter.WithHint("One of 'subject' or 'allow_any_subject' field must be set."))
}
if request.Subject != "" && request.AllowAnySubject {
return errorsx.WithStack(ErrMissingRequiredParameter.WithHint("Both 'subject' and 'allow_any_subject' fields cannot be set at the same time."))
}
if request.ExpiresAt.IsZero() {
return errorsx.WithStack(ErrMissingRequiredParameter.WithHint("Field 'expires_at' is required."))
}
if request.PublicKeyJWK.KeyID == "" {
return errorsx.WithStack(ErrMissingRequiredParameter.WithHint("Field 'jwk' must contain JWK with kid header."))
}
return nil
} |
Go | hydra/oauth2/trust/validator_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package trust
import (
"testing"
"time"
"github.com/go-jose/go-jose/v3"
)
func TestEmptyIssuerIsInvalid(t *testing.T) {
v := GrantValidator{}
r := createGrantRequest{
Issuer: "",
Subject: "valid-subject",
AllowAnySubject: false,
ExpiresAt: time.Now().Add(time.Hour * 10),
PublicKeyJWK: jose.JSONWebKey{
KeyID: "valid-key-id",
},
}
if err := v.Validate(r); err == nil {
t.Error("an empty issuer should not be valid")
}
}
func TestEmptySubjectAndNoAnySubjectFlagIsInvalid(t *testing.T) {
v := GrantValidator{}
r := createGrantRequest{
Issuer: "valid-issuer",
Subject: "",
AllowAnySubject: false,
ExpiresAt: time.Now().Add(time.Hour * 10),
PublicKeyJWK: jose.JSONWebKey{
KeyID: "valid-key-id",
},
}
if err := v.Validate(r); err == nil {
t.Error("an empty subject should not be valid")
}
}
func TestEmptySubjectWithAnySubjectFlagIsValid(t *testing.T) {
v := GrantValidator{}
r := createGrantRequest{
Issuer: "valid-issuer",
Subject: "",
AllowAnySubject: true,
ExpiresAt: time.Now().Add(time.Hour * 10),
PublicKeyJWK: jose.JSONWebKey{
KeyID: "valid-key-id",
},
}
if err := v.Validate(r); err != nil {
t.Error("an empty subject with the allow_any_subject flag should be valid")
}
}
func TestNonEmptySubjectWithAnySubjectFlagIsInvalid(t *testing.T) {
v := GrantValidator{}
r := createGrantRequest{
Issuer: "valid-issuer",
Subject: "some-issuer",
AllowAnySubject: true,
ExpiresAt: time.Now().Add(time.Hour * 10),
PublicKeyJWK: jose.JSONWebKey{
KeyID: "valid-key-id",
},
}
if err := v.Validate(r); err == nil {
t.Error("a non empty subject with the allow_any_subject flag should not be valid")
}
}
func TestEmptyExpiresAtIsInvalid(t *testing.T) {
v := GrantValidator{}
r := createGrantRequest{
Issuer: "valid-issuer",
Subject: "valid-subject",
AllowAnySubject: false,
ExpiresAt: time.Time{},
PublicKeyJWK: jose.JSONWebKey{
KeyID: "valid-key-id",
},
}
if err := v.Validate(r); err == nil {
t.Error("an empty expiration should not be valid")
}
}
func TestEmptyPublicKeyIdIsInvalid(t *testing.T) {
v := GrantValidator{}
r := createGrantRequest{
Issuer: "valid-issuer",
Subject: "valid-subject",
AllowAnySubject: false,
ExpiresAt: time.Now().Add(time.Hour * 10),
PublicKeyJWK: jose.JSONWebKey{
KeyID: "",
},
}
if err := v.Validate(r); err == nil {
t.Error("an empty public key id should not be valid")
}
}
func TestIsValid(t *testing.T) {
v := GrantValidator{}
r := createGrantRequest{
Issuer: "valid-issuer",
Subject: "valid-subject",
AllowAnySubject: false,
ExpiresAt: time.Now().Add(time.Hour * 10),
PublicKeyJWK: jose.JSONWebKey{
KeyID: "valid-key-id",
},
}
if err := v.Validate(r); err != nil {
t.Error("A request with an issuer, a subject, an expiration and a public key should be valid")
}
} |
Go | hydra/persistence/definitions.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package persistence
import (
"context"
"github.com/gofrs/uuid"
"github.com/ory/x/networkx"
"github.com/gobuffalo/pop/v6"
"github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/consent"
"github.com/ory/hydra/v2/jwk"
"github.com/ory/hydra/v2/oauth2/trust"
"github.com/ory/hydra/v2/x"
"github.com/ory/x/popx"
)
type (
Persister interface {
consent.Manager
client.Manager
x.FositeStorer
jwk.Manager
trust.GrantManager
MigrationStatus(ctx context.Context) (popx.MigrationStatuses, error)
MigrateDown(context.Context, int) error
MigrateUp(context.Context) error
PrepareMigration(context.Context) error
Connection(context.Context) *pop.Connection
Ping() error
Networker
}
Provider interface {
Persister() Persister
}
Networker interface {
NetworkID(ctx context.Context) uuid.UUID
DetermineNetwork(ctx context.Context) (*networkx.Network, error)
}
) |
Go | hydra/persistence/sql/persister.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package sql
import (
"context"
"database/sql"
"io/fs"
"reflect"
"github.com/gobuffalo/pop/v6"
"github.com/gofrs/uuid"
"github.com/pkg/errors"
"github.com/ory/fosite"
"github.com/ory/fosite/storage"
"github.com/ory/hydra/v2/aead"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/persistence"
"github.com/ory/hydra/v2/x"
"github.com/ory/x/contextx"
"github.com/ory/x/errorsx"
"github.com/ory/x/fsx"
"github.com/ory/x/logrusx"
"github.com/ory/x/networkx"
"github.com/ory/x/otelx"
"github.com/ory/x/popx"
)
var _ persistence.Persister = new(Persister)
var _ storage.Transactional = new(Persister)
var (
ErrTransactionOpen = errors.New("There is already a transaction in this context.")
ErrNoTransactionOpen = errors.New("There is no transaction in this context.")
)
type (
Persister struct {
conn *pop.Connection
mb *popx.MigrationBox
mbs popx.MigrationStatuses
r Dependencies
config *config.DefaultProvider
l *logrusx.Logger
fallbackNID uuid.UUID
p *networkx.Manager
}
Dependencies interface {
ClientHasher() fosite.Hasher
KeyCipher() *aead.AESGCM
FlowCipher() *aead.XChaCha20Poly1305
contextx.Provider
x.RegistryLogger
x.TracingProvider
}
)
func (p *Persister) BeginTX(ctx context.Context) (_ context.Context, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.BeginTX")
defer otelx.End(span, &err)
fallback := &pop.Connection{TX: &pop.Tx{}}
if popx.GetConnection(ctx, fallback).TX != fallback.TX {
return ctx, errorsx.WithStack(ErrTransactionOpen)
}
tx, err := p.conn.Store.TransactionContextOptions(ctx, &sql.TxOptions{
Isolation: sql.LevelRepeatableRead,
ReadOnly: false,
})
c := &pop.Connection{
TX: tx,
Store: tx,
ID: uuid.Must(uuid.NewV4()).String(),
Dialect: p.conn.Dialect,
}
return popx.WithTransaction(ctx, c), err
}
func (p *Persister) Commit(ctx context.Context) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.Commit")
defer otelx.End(span, &err)
fallback := &pop.Connection{TX: &pop.Tx{}}
tx := popx.GetConnection(ctx, fallback)
if tx.TX == fallback.TX || tx.TX == nil {
return errorsx.WithStack(ErrNoTransactionOpen)
}
return errorsx.WithStack(tx.TX.Commit())
}
func (p *Persister) Rollback(ctx context.Context) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.Rollback")
defer otelx.End(span, &err)
fallback := &pop.Connection{TX: &pop.Tx{}}
tx := popx.GetConnection(ctx, fallback)
if tx.TX == fallback.TX || tx.TX == nil {
return errorsx.WithStack(ErrNoTransactionOpen)
}
return errorsx.WithStack(tx.TX.Rollback())
}
func NewPersister(ctx context.Context, c *pop.Connection, r Dependencies, config *config.DefaultProvider, extraMigrations []fs.FS, goMigrations []popx.Migration) (*Persister, error) {
mb, err := popx.NewMigrationBox(
fsx.Merge(append([]fs.FS{migrations}, extraMigrations...)...),
popx.NewMigrator(c, r.Logger(), r.Tracer(ctx), 0),
popx.WithGoMigrations(goMigrations))
if err != nil {
return nil, errorsx.WithStack(err)
}
return &Persister{
conn: c,
mb: mb,
r: r,
config: config,
l: r.Logger(),
p: networkx.NewManager(c, r.Logger(), r.Tracer(ctx)),
}, nil
}
func (p *Persister) DetermineNetwork(ctx context.Context) (*networkx.Network, error) {
return p.p.Determine(ctx)
}
func (p Persister) WithFallbackNetworkID(nid uuid.UUID) persistence.Persister {
p.fallbackNID = nid
return &p
}
func (p *Persister) CreateWithNetwork(ctx context.Context, v interface{}) error {
n := p.NetworkID(ctx)
return p.Connection(ctx).Create(p.mustSetNetwork(n, v))
}
func (p *Persister) UpdateWithNetwork(ctx context.Context, v interface{}) (int64, error) {
n := p.NetworkID(ctx)
v = p.mustSetNetwork(n, v)
m := pop.NewModel(v, ctx)
var cs []string
for _, t := range m.Columns().Cols {
cs = append(cs, t.Name)
}
return p.Connection(ctx).Where(m.IDField()+" = ? AND nid = ?", m.ID(), n).UpdateQuery(v, cs...)
}
func (p *Persister) NetworkID(ctx context.Context) uuid.UUID {
return p.r.Contextualizer().Network(ctx, p.fallbackNID)
}
func (p *Persister) QueryWithNetwork(ctx context.Context) *pop.Query {
return p.Connection(ctx).Where("nid = ?", p.NetworkID(ctx))
}
func (p *Persister) Connection(ctx context.Context) *pop.Connection {
return popx.GetConnection(ctx, p.conn)
}
func (p *Persister) Ping() error {
type pinger interface{ Ping() error }
return p.conn.Store.(pinger).Ping()
}
func (p *Persister) mustSetNetwork(nid uuid.UUID, v interface{}) interface{} {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr || (rv.Kind() == reflect.Ptr && rv.Elem().Kind() != reflect.Struct) {
panic("v must be a pointer to a struct")
}
nf := rv.Elem().FieldByName("NID")
if !nf.IsValid() || !nf.CanSet() {
panic("v must have settable a field 'NID uuid.UUID'")
}
nf.Set(reflect.ValueOf(nid))
return v
}
func (p *Persister) transaction(ctx context.Context, f func(ctx context.Context, c *pop.Connection) error) error {
return popx.Transaction(ctx, p.conn, f)
} |
Go | hydra/persistence/sql/persister_client.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package sql
import (
"context"
"github.com/ory/hydra/v2/x/events"
"github.com/gobuffalo/pop/v6"
"github.com/gofrs/uuid"
"github.com/ory/x/errorsx"
"github.com/ory/x/otelx"
"github.com/ory/fosite"
"github.com/ory/hydra/v2/client"
"github.com/ory/x/sqlcon"
)
func (p *Persister) GetConcreteClient(ctx context.Context, id string) (c *client.Client, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetConcreteClient")
defer otelx.End(span, &err)
var cl client.Client
if err := p.QueryWithNetwork(ctx).Where("id = ?", id).First(&cl); err != nil {
return nil, sqlcon.HandleError(err)
}
return &cl, nil
}
func (p *Persister) GetClient(ctx context.Context, id string) (fosite.Client, error) {
return p.GetConcreteClient(ctx, id)
}
func (p *Persister) UpdateClient(ctx context.Context, cl *client.Client) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.UpdateClient")
defer otelx.End(span, &err)
return p.transaction(ctx, func(ctx context.Context, c *pop.Connection) error {
o, err := p.GetConcreteClient(ctx, cl.GetID())
if err != nil {
return err
}
if cl.Secret == "" {
cl.Secret = string(o.GetHashedSecret())
} else {
h, err := p.r.ClientHasher().Hash(ctx, []byte(cl.Secret))
if err != nil {
return errorsx.WithStack(err)
}
cl.Secret = string(h)
}
// set the internal primary key
cl.ID = o.ID
// Set the legacy client ID
cl.LegacyClientID = o.LegacyClientID
if err = cl.BeforeSave(c); err != nil {
return sqlcon.HandleError(err)
}
count, err := p.UpdateWithNetwork(ctx, cl)
if err != nil {
return sqlcon.HandleError(err)
} else if count == 0 {
return sqlcon.HandleError(sqlcon.ErrNoRows)
}
events.Trace(ctx, events.ClientUpdated,
events.WithClientID(cl.ID.String()),
events.WithClientName(cl.Name))
return sqlcon.HandleError(err)
})
}
func (p *Persister) Authenticate(ctx context.Context, id string, secret []byte) (_ *client.Client, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.Authenticate")
defer otelx.End(span, &err)
c, err := p.GetConcreteClient(ctx, id)
if err != nil {
return nil, errorsx.WithStack(err)
}
if err := p.r.ClientHasher().Compare(ctx, c.GetHashedSecret(), secret); err != nil {
return nil, errorsx.WithStack(err)
}
return c, nil
}
func (p *Persister) CreateClient(ctx context.Context, c *client.Client) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.CreateClient")
defer otelx.End(span, &err)
h, err := p.r.ClientHasher().Hash(ctx, []byte(c.Secret))
if err != nil {
return err
}
c.Secret = string(h)
if c.ID == uuid.Nil {
c.ID = uuid.Must(uuid.NewV4())
}
if c.LegacyClientID == "" {
c.LegacyClientID = c.ID.String()
}
if err := sqlcon.HandleError(p.CreateWithNetwork(ctx, c)); err != nil {
return err
}
events.Trace(ctx, events.ClientCreated,
events.WithClientID(c.ID.String()),
events.WithClientName(c.Name))
return nil
}
func (p *Persister) DeleteClient(ctx context.Context, id string) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.DeleteClient")
defer otelx.End(span, &err)
c, err := p.GetConcreteClient(ctx, id)
if err != nil {
return err
}
if err := sqlcon.HandleError(p.QueryWithNetwork(ctx).Where("id = ?", id).Delete(&client.Client{})); err != nil {
return err
}
events.Trace(ctx, events.ClientDeleted,
events.WithClientID(c.ID.String()),
events.WithClientName(c.Name))
return nil
}
func (p *Persister) GetClients(ctx context.Context, filters client.Filter) (_ []client.Client, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetClients")
defer otelx.End(span, &err)
cs := make([]client.Client, 0)
query := p.QueryWithNetwork(ctx).
Paginate(filters.Offset/filters.Limit+1, filters.Limit).
Order("pk")
if filters.Name != "" {
query.Where("client_name = ?", filters.Name)
}
if filters.Owner != "" {
query.Where("owner = ?", filters.Owner)
}
if err := query.All(&cs); err != nil {
return nil, sqlcon.HandleError(err)
}
return cs, nil
}
func (p *Persister) CountClients(ctx context.Context) (n int, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.CountClients")
defer otelx.End(span, &err)
n, err = p.QueryWithNetwork(ctx).Count(&client.Client{})
return n, sqlcon.HandleError(err)
} |
Go | hydra/persistence/sql/persister_consent.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package sql
import (
"context"
"database/sql"
"fmt"
"strings"
"time"
"github.com/gobuffalo/pop/v6"
"github.com/gofrs/uuid"
"github.com/ory/hydra/v2/oauth2/flowctx"
"github.com/ory/x/otelx"
"github.com/ory/x/sqlxx"
"github.com/ory/x/errorsx"
"github.com/pkg/errors"
"github.com/ory/fosite"
"github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/consent"
"github.com/ory/hydra/v2/flow"
"github.com/ory/hydra/v2/x"
"github.com/ory/x/sqlcon"
)
var _ consent.Manager = &Persister{}
func (p *Persister) RevokeSubjectConsentSession(ctx context.Context, user string) error {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.RevokeSubjectConsentSession")
defer span.End()
return p.transaction(ctx, p.revokeConsentSession("consent_challenge_id IS NOT NULL AND subject = ?", user))
}
func (p *Persister) RevokeSubjectClientConsentSession(ctx context.Context, user, client string) error {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.RevokeSubjectClientConsentSession")
defer span.End()
return p.transaction(ctx, p.revokeConsentSession("consent_challenge_id IS NOT NULL AND subject = ? AND client_id = ?", user, client))
}
func (p *Persister) revokeConsentSession(whereStmt string, whereArgs ...interface{}) func(context.Context, *pop.Connection) error {
return func(ctx context.Context, c *pop.Connection) error {
fs := make([]*flow.Flow, 0)
if err := p.QueryWithNetwork(ctx).
Where(whereStmt, whereArgs...).
Select("consent_challenge_id").
All(&fs); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return errorsx.WithStack(x.ErrNotFound)
}
return sqlcon.HandleError(err)
}
var count int
for _, f := range fs {
if err := p.RevokeAccessToken(ctx, f.ConsentChallengeID.String()); errors.Is(err, fosite.ErrNotFound) {
// do nothing
} else if err != nil {
return err
}
if err := p.RevokeRefreshToken(ctx, f.ConsentChallengeID.String()); errors.Is(err, fosite.ErrNotFound) {
// do nothing
} else if err != nil {
return err
}
localCount, err := c.RawQuery("DELETE FROM hydra_oauth2_flow WHERE consent_challenge_id = ? AND nid = ?", f.ConsentChallengeID, p.NetworkID(ctx)).ExecWithCount()
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return errorsx.WithStack(x.ErrNotFound)
}
return sqlcon.HandleError(err)
}
// If there are no sessions to revoke we should return an error to indicate to the caller
// that the request failed.
count += localCount
}
if count == 0 {
return errorsx.WithStack(x.ErrNotFound)
}
return nil
}
}
func (p *Persister) RevokeSubjectLoginSession(ctx context.Context, subject string) error {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.RevokeSubjectLoginSession")
defer span.End()
err := p.QueryWithNetwork(ctx).Where("subject = ?", subject).Delete(&flow.LoginSession{})
if err != nil {
return sqlcon.HandleError(err)
}
// This confuses people, see https://github.com/ory/hydra/issues/1168
//
// count, _ := rows.RowsAffected()
// if count == 0 {
// return errorsx.WithStack(x.ErrNotFound)
// }
return nil
}
func (p *Persister) CreateForcedObfuscatedLoginSession(ctx context.Context, session *consent.ForcedObfuscatedLoginSession) error {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.CreateForcedObfuscatedLoginSession")
defer span.End()
return p.transaction(ctx, func(ctx context.Context, c *pop.Connection) error {
nid := p.NetworkID(ctx)
if err := c.RawQuery(
"DELETE FROM hydra_oauth2_obfuscated_authentication_session WHERE nid = ? AND client_id = ? AND subject = ?",
nid,
session.ClientID,
session.Subject,
).Exec(); err != nil {
return sqlcon.HandleError(err)
}
return sqlcon.HandleError(c.RawQuery(
"INSERT INTO hydra_oauth2_obfuscated_authentication_session (nid, subject, client_id, subject_obfuscated) VALUES (?, ?, ?, ?)",
nid,
session.Subject,
session.ClientID,
session.SubjectObfuscated,
).Exec())
})
}
func (p *Persister) GetForcedObfuscatedLoginSession(ctx context.Context, client, obfuscated string) (*consent.ForcedObfuscatedLoginSession, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetForcedObfuscatedLoginSession")
defer span.End()
var s consent.ForcedObfuscatedLoginSession
if err := p.Connection(ctx).Where(
"client_id = ? AND subject_obfuscated = ? AND nid = ?",
client,
obfuscated,
p.NetworkID(ctx),
).First(&s); errors.Is(err, sql.ErrNoRows) {
return nil, errorsx.WithStack(x.ErrNotFound)
} else if err != nil {
return nil, sqlcon.HandleError(err)
}
return &s, nil
}
// CreateConsentRequest configures fields that are introduced or changed in the
// consent request. It doesn't touch fields that would be copied from the login
// request.
func (p *Persister) CreateConsentRequest(ctx context.Context, f *flow.Flow, req *flow.OAuth2ConsentRequest) error {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.CreateConsentRequest")
defer span.End()
if f == nil {
return errorsx.WithStack(x.ErrNotFound.WithDebug("Flow is nil"))
}
if f.ID != req.LoginChallenge.String() || f.NID != p.NetworkID(ctx) {
return errorsx.WithStack(x.ErrNotFound)
}
f.State = flow.FlowStateConsentInitialized
f.ConsentChallengeID = sqlxx.NullString(req.ID)
f.ConsentSkip = req.Skip
f.ConsentVerifier = sqlxx.NullString(req.Verifier)
f.ConsentCSRF = sqlxx.NullString(req.CSRF)
return nil
}
func (p *Persister) GetFlowByConsentChallenge(ctx context.Context, challenge string) (*flow.Flow, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetFlowByConsentChallenge")
defer span.End()
// challenge contains the flow.
f, err := flowctx.Decode[flow.Flow](ctx, p.r.FlowCipher(), challenge, flowctx.AsConsentChallenge)
if err != nil {
return nil, errorsx.WithStack(x.ErrNotFound)
}
if f.NID != p.NetworkID(ctx) {
return nil, errorsx.WithStack(x.ErrNotFound)
}
if f.RequestedAt.Add(p.config.ConsentRequestMaxAge(ctx)).Before(time.Now()) {
return nil, errorsx.WithStack(fosite.ErrRequestUnauthorized.WithHint("The consent request has expired, please try again."))
}
return f, nil
}
func (p *Persister) GetConsentRequest(ctx context.Context, challenge string) (*flow.OAuth2ConsentRequest, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetConsentRequest")
defer span.End()
f, err := p.GetFlowByConsentChallenge(ctx, challenge)
if err != nil {
if errors.Is(err, sqlcon.ErrNoRows) {
return nil, errorsx.WithStack(x.ErrNotFound)
}
return nil, err
}
// We need to overwrite the ID with the encoded flow (challenge) so that the client is not confused.
f.ConsentChallengeID = sqlxx.NullString(challenge)
return f.GetConsentRequest(), nil
}
func (p *Persister) CreateLoginRequest(ctx context.Context, req *flow.LoginRequest) (*flow.Flow, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.CreateLoginRequest")
defer span.End()
f := flow.NewFlow(req)
nid := p.NetworkID(ctx)
if nid == uuid.Nil {
return nil, errorsx.WithStack(x.ErrNotFound)
}
f.NID = nid
return f, nil
}
func (p *Persister) GetFlow(ctx context.Context, loginChallenge string) (*flow.Flow, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetFlow")
defer span.End()
var f flow.Flow
if err := p.QueryWithNetwork(ctx).Where("login_challenge = ?", loginChallenge).First(&f); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, errorsx.WithStack(x.ErrNotFound)
}
return nil, sqlcon.HandleError(err)
}
return &f, nil
}
func (p *Persister) GetLoginRequest(ctx context.Context, loginChallenge string) (*flow.LoginRequest, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetLoginRequest")
defer span.End()
f, err := flowctx.Decode[flow.Flow](ctx, p.r.FlowCipher(), loginChallenge, flowctx.AsLoginChallenge)
if err != nil {
return nil, errorsx.WithStack(x.ErrNotFound.WithWrap(err))
}
if f.NID != p.NetworkID(ctx) {
return nil, errorsx.WithStack(x.ErrNotFound)
}
if f.RequestedAt.Add(p.config.ConsentRequestMaxAge(ctx)).Before(time.Now()) {
return nil, errorsx.WithStack(fosite.ErrRequestUnauthorized.WithHint("The login request has expired, please try again."))
}
lr := f.GetLoginRequest()
// Restore the short challenge ID, which was previously sent to the encoded flow,
// to make sure that the challenge ID in the returned flow matches the param.
lr.ID = loginChallenge
return lr, nil
}
func (p *Persister) HandleConsentRequest(ctx context.Context, f *flow.Flow, r *flow.AcceptOAuth2ConsentRequest) (*flow.OAuth2ConsentRequest, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.HandleConsentRequest")
defer span.End()
if f == nil {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithDebug("Flow was nil"))
}
if f.NID != p.NetworkID(ctx) {
return nil, errorsx.WithStack(x.ErrNotFound)
}
// Restore the short challenge ID, which was previously sent to the encoded flow,
// to make sure that the challenge ID in the returned flow matches the param.
r.ID = f.ConsentChallengeID.String()
if err := f.HandleConsentRequest(r); err != nil {
return nil, errorsx.WithStack(err)
}
return f.GetConsentRequest(), nil
}
func (p *Persister) VerifyAndInvalidateConsentRequest(ctx context.Context, f *flow.Flow, verifier string) (*flow.AcceptOAuth2ConsentRequest, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.VerifyAndInvalidateConsentRequest")
defer span.End()
if f == nil {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithDebug("Flow was nil"))
}
if f.NID != p.NetworkID(ctx) {
return nil, errorsx.WithStack(sqlcon.ErrNoRows)
}
updatedFlow, err := flowctx.Decode[flow.Flow](ctx, p.r.FlowCipher(), verifier, flowctx.AsConsentVerifier)
if err != nil {
return nil, errorsx.WithStack(fosite.ErrAccessDenied.WithHint("The consent verifier has already been used, has not been granted, or is invalid."))
}
if updatedFlow.ID != f.ID {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithDebug("Consent verifier does not match login request."))
}
if updatedFlow.NID != p.NetworkID(ctx) {
return nil, errorsx.WithStack(sqlcon.ErrNoRows)
}
// Update flow from login request, but keep requested at.
updatedFlow.NID = f.NID
updatedFlow.ConsentCSRF = f.ConsentCSRF
updatedFlow.ConsentVerifier = f.ConsentVerifier
*f = *updatedFlow
if err = f.InvalidateConsentRequest(); err != nil {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithDebug(err.Error()))
}
// We set the consent challenge ID to a new UUID that we can use as a foreign key in the database
// without encoding the whole flow.
f.ConsentChallengeID = sqlxx.NullString(uuid.Must(uuid.NewV4()).String())
if err = p.Connection(ctx).Create(f); err != nil {
return nil, sqlcon.HandleError(err)
}
return f.GetHandledConsentRequest(), nil
}
func (p *Persister) HandleLoginRequest(ctx context.Context, f *flow.Flow, challenge string, r *flow.HandledLoginRequest) (lr *flow.LoginRequest, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.HandleLoginRequest")
defer span.End()
if f == nil {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithDebug("Flow was nil"))
}
if f.NID != p.NetworkID(ctx) {
return nil, errorsx.WithStack(x.ErrNotFound)
}
r.ID = f.ID
err = f.HandleLoginRequest(r)
if err != nil {
return nil, err
}
return p.GetLoginRequest(ctx, challenge)
}
func (p *Persister) VerifyAndInvalidateLoginRequest(ctx context.Context, f *flow.Flow, verifier string) (*flow.HandledLoginRequest, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.VerifyAndInvalidateLoginRequest")
defer span.End()
if f == nil {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithDebug("Flow was nil"))
}
if f.NID != p.NetworkID(ctx) {
return nil, errorsx.WithStack(sqlcon.ErrNoRows)
}
updatedFlow, err := flowctx.Decode[flow.Flow](ctx, p.r.FlowCipher(), verifier, flowctx.AsLoginVerifier)
if err != nil {
return nil, errorsx.WithStack(sqlcon.ErrNoRows)
}
if f.NID != updatedFlow.NID {
return nil, errorsx.WithStack(sqlcon.ErrNoRows)
}
if updatedFlow.ID != f.ID {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithDebug("Login verifier does not match login request."))
}
// Update flow from login request, but keep requested at.
updatedFlow.NID = f.NID
updatedFlow.RequestedAt = f.RequestedAt
updatedFlow.LoginCSRF = f.LoginCSRF
updatedFlow.LoginVerifier = f.LoginVerifier
*f = *updatedFlow
if err := f.InvalidateLoginRequest(); err != nil {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithDebug(err.Error()))
}
d := f.GetHandledLoginRequest()
return &d, nil
}
func (p *Persister) GetRememberedLoginSession(ctx context.Context, loginSessionFromCookie *flow.LoginSession, id string) (*flow.LoginSession, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetRememberedLoginSession")
defer span.End()
if s := loginSessionFromCookie; s != nil && s.NID == p.NetworkID(ctx) && s.ID == id && s.Remember {
return s, nil
}
var s flow.LoginSession
if err := p.QueryWithNetwork(ctx).Where("remember = TRUE").Find(&s, id); errors.Is(err, sql.ErrNoRows) {
return nil, errorsx.WithStack(x.ErrNotFound)
} else if err != nil {
return nil, sqlcon.HandleError(err)
}
return &s, nil
}
func (p *Persister) ConfirmLoginSession(ctx context.Context, session *flow.LoginSession, id string, authenticatedAt time.Time, subject string, remember bool) error {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.ConfirmLoginSession")
defer span.End()
// Since we previously cached the login session, we now need to persist it to db.
if session != nil {
if session.NID != p.NetworkID(ctx) || session.ID != id {
return errorsx.WithStack(x.ErrNotFound)
}
session.AuthenticatedAt = sqlxx.NullTime(authenticatedAt.Truncate(time.Second))
session.Subject = subject
session.Remember = remember
return p.CreateWithNetwork(ctx, session)
}
// In some unit tests, we still confirm the login session without data from the cookie. We can remove this case
// once all tests are fixed.
n, err := p.Connection(ctx).Where("id = ? AND nid = ?", id, p.NetworkID(ctx)).UpdateQuery(&flow.LoginSession{
AuthenticatedAt: sqlxx.NullTime(authenticatedAt),
Subject: subject,
Remember: remember,
}, "authenticated_at", "subject", "remember")
if err != nil {
return sqlcon.HandleError(err)
}
if n == 0 {
return errorsx.WithStack(x.ErrNotFound)
}
return nil
}
func (p *Persister) CreateLoginSession(ctx context.Context, session *flow.LoginSession) error {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.CreateLoginSession")
defer span.End()
nid := p.NetworkID(ctx)
if nid == uuid.Nil {
return errorsx.WithStack(x.ErrNotFound)
}
session.NID = nid
return nil
}
func (p *Persister) DeleteLoginSession(ctx context.Context, id string) (deletedSession *flow.LoginSession, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.DeleteLoginSession")
defer otelx.End(span, &err)
if p.Connection(ctx).Dialect.Name() == "mysql" {
// MySQL does not support RETURNING.
return p.mySQLDeleteLoginSession(ctx, id)
}
var session flow.LoginSession
err = p.Connection(ctx).RawQuery(
`DELETE FROM hydra_oauth2_authentication_session
WHERE id = ? AND nid = ?
RETURNING *`,
id,
p.NetworkID(ctx),
).First(&session)
if err != nil {
return nil, sqlcon.HandleError(err)
}
return &session, nil
}
func (p *Persister) mySQLDeleteLoginSession(ctx context.Context, id string) (*flow.LoginSession, error) {
var session flow.LoginSession
err := p.Connection(ctx).Transaction(func(tx *pop.Connection) error {
err := tx.RawQuery(`
SELECT * FROM hydra_oauth2_authentication_session
WHERE id = ? AND nid = ?`,
id,
p.NetworkID(ctx),
).First(&session)
if err != nil {
return err
}
return p.Connection(ctx).RawQuery(`
DELETE FROM hydra_oauth2_authentication_session
WHERE id = ? AND nid = ?`,
id,
p.NetworkID(ctx),
).Exec()
})
if err != nil {
return nil, sqlcon.HandleError(err)
}
return &session, nil
}
func (p *Persister) FindGrantedAndRememberedConsentRequests(ctx context.Context, client, subject string) (rs []flow.AcceptOAuth2ConsentRequest, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.FindGrantedAndRememberedConsentRequests")
defer span.End()
var f flow.Flow
if err = p.Connection(ctx).
Where(
strings.TrimSpace(fmt.Sprintf(`
(state = %d OR state = %d) AND
subject = ? AND
client_id = ? AND
consent_skip=FALSE AND
consent_error='{}' AND
consent_remember=TRUE AND
nid = ?`, flow.FlowStateConsentUsed, flow.FlowStateConsentUnused,
)),
subject, client, p.NetworkID(ctx)).
Order("requested_at DESC").
Limit(1).
First(&f); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, errorsx.WithStack(consent.ErrNoPreviousConsentFound)
}
return nil, sqlcon.HandleError(err)
}
return p.filterExpiredConsentRequests(ctx, []flow.AcceptOAuth2ConsentRequest{*f.GetHandledConsentRequest()})
}
func (p *Persister) FindSubjectsGrantedConsentRequests(ctx context.Context, subject string, limit, offset int) ([]flow.AcceptOAuth2ConsentRequest, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.FindSubjectsGrantedConsentRequests")
defer span.End()
var fs []flow.Flow
c := p.Connection(ctx)
if err := c.
Where(
strings.TrimSpace(fmt.Sprintf(`
(state = %d OR state = %d) AND
subject = ? AND
consent_skip=FALSE AND
consent_error='{}' AND
nid = ?`, flow.FlowStateConsentUsed, flow.FlowStateConsentUnused,
)),
subject, p.NetworkID(ctx)).
Order("requested_at DESC").
Paginate(offset/limit+1, limit).
All(&fs); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, errorsx.WithStack(consent.ErrNoPreviousConsentFound)
}
return nil, sqlcon.HandleError(err)
}
var rs []flow.AcceptOAuth2ConsentRequest
for _, f := range fs {
rs = append(rs, *f.GetHandledConsentRequest())
}
return p.filterExpiredConsentRequests(ctx, rs)
}
func (p *Persister) FindSubjectsSessionGrantedConsentRequests(ctx context.Context, subject, sid string, limit, offset int) ([]flow.AcceptOAuth2ConsentRequest, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.FindSubjectsSessionGrantedConsentRequests")
defer span.End()
var fs []flow.Flow
c := p.Connection(ctx)
if err := c.
Where(
strings.TrimSpace(fmt.Sprintf(`
(state = %d OR state = %d) AND
subject = ? AND
login_session_id = ? AND
consent_skip=FALSE AND
consent_error='{}' AND
nid = ?`, flow.FlowStateConsentUsed, flow.FlowStateConsentUnused,
)),
subject, sid, p.NetworkID(ctx)).
Order("requested_at DESC").
Paginate(offset/limit+1, limit).
All(&fs); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, errorsx.WithStack(consent.ErrNoPreviousConsentFound)
}
return nil, sqlcon.HandleError(err)
}
var rs []flow.AcceptOAuth2ConsentRequest
for _, f := range fs {
rs = append(rs, *f.GetHandledConsentRequest())
}
return p.filterExpiredConsentRequests(ctx, rs)
}
func (p *Persister) CountSubjectsGrantedConsentRequests(ctx context.Context, subject string) (int, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.CountSubjectsGrantedConsentRequests")
defer span.End()
n, err := p.Connection(ctx).
Where(
strings.TrimSpace(fmt.Sprintf(`
(state = %d OR state = %d) AND
subject = ? AND
consent_skip=FALSE AND
consent_error='{}' AND
nid = ?`, flow.FlowStateConsentUsed, flow.FlowStateConsentUnused,
)),
subject, p.NetworkID(ctx)).
Count(&flow.Flow{})
return n, sqlcon.HandleError(err)
}
func (p *Persister) filterExpiredConsentRequests(ctx context.Context, requests []flow.AcceptOAuth2ConsentRequest) ([]flow.AcceptOAuth2ConsentRequest, error) {
_, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.filterExpiredConsentRequests")
defer span.End()
var result []flow.AcceptOAuth2ConsentRequest
for _, v := range requests {
if v.RememberFor > 0 && v.RequestedAt.Add(time.Duration(v.RememberFor)*time.Second).Before(time.Now().UTC()) {
continue
}
result = append(result, v)
}
if len(result) == 0 {
return nil, errorsx.WithStack(consent.ErrNoPreviousConsentFound)
}
return result, nil
}
func (p *Persister) ListUserAuthenticatedClientsWithFrontChannelLogout(ctx context.Context, subject, sid string) ([]client.Client, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.ListUserAuthenticatedClientsWithFrontChannelLogout")
defer span.End()
return p.listUserAuthenticatedClients(ctx, subject, sid, "front")
}
func (p *Persister) ListUserAuthenticatedClientsWithBackChannelLogout(ctx context.Context, subject, sid string) ([]client.Client, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.ListUserAuthenticatedClientsWithBackChannelLogout")
defer span.End()
return p.listUserAuthenticatedClients(ctx, subject, sid, "back")
}
func (p *Persister) listUserAuthenticatedClients(ctx context.Context, subject, sid, channel string) ([]client.Client, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.listUserAuthenticatedClients")
defer span.End()
var cs []client.Client
if err := p.Connection(ctx).RawQuery(
/* #nosec G201 - channel can either be "front" or "back" */
fmt.Sprintf(`
SELECT DISTINCT c.* FROM hydra_client as c
JOIN hydra_oauth2_flow as f ON (c.id = f.client_id)
WHERE
f.subject=? AND
c.%schannel_logout_uri!='' AND
c.%schannel_logout_uri IS NOT NULL AND
f.login_session_id = ? AND
f.nid = ? AND
c.nid = ?`,
channel,
channel,
),
subject,
sid,
p.NetworkID(ctx),
p.NetworkID(ctx),
).All(&cs); err != nil {
return nil, sqlcon.HandleError(err)
}
return cs, nil
}
func (p *Persister) CreateLogoutRequest(ctx context.Context, request *flow.LogoutRequest) error {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.CreateLogoutRequest")
defer span.End()
return errorsx.WithStack(p.CreateWithNetwork(ctx, request))
}
func (p *Persister) AcceptLogoutRequest(ctx context.Context, challenge string) (*flow.LogoutRequest, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.AcceptLogoutRequest")
defer span.End()
if err := p.Connection(ctx).RawQuery("UPDATE hydra_oauth2_logout_request SET accepted=true, rejected=false WHERE challenge=? AND nid = ?", challenge, p.NetworkID(ctx)).Exec(); err != nil {
return nil, sqlcon.HandleError(err)
}
return p.GetLogoutRequest(ctx, challenge)
}
func (p *Persister) RejectLogoutRequest(ctx context.Context, challenge string) error {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.RejectLogoutRequest")
defer span.End()
count, err := p.Connection(ctx).
RawQuery("UPDATE hydra_oauth2_logout_request SET rejected=true, accepted=false WHERE challenge=? AND nid = ?", challenge, p.NetworkID(ctx)).
ExecWithCount()
if count == 0 {
return errorsx.WithStack(x.ErrNotFound)
} else {
return errorsx.WithStack(err)
}
}
func (p *Persister) GetLogoutRequest(ctx context.Context, challenge string) (*flow.LogoutRequest, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetLogoutRequest")
defer span.End()
var lr flow.LogoutRequest
return &lr, sqlcon.HandleError(p.QueryWithNetwork(ctx).Where("challenge = ? AND rejected = FALSE", challenge).First(&lr))
}
func (p *Persister) VerifyAndInvalidateLogoutRequest(ctx context.Context, verifier string) (*flow.LogoutRequest, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.VerifyAndInvalidateLogoutRequest")
defer span.End()
var lr flow.LogoutRequest
if count, err := p.Connection(ctx).RawQuery(
"UPDATE hydra_oauth2_logout_request SET was_used=TRUE WHERE nid = ? AND verifier=? AND was_used=FALSE AND accepted=TRUE AND rejected=FALSE",
p.NetworkID(ctx),
verifier,
).ExecWithCount(); count == 0 && err == nil {
return nil, errorsx.WithStack(x.ErrNotFound)
} else if err != nil {
return nil, sqlcon.HandleError(err)
}
err := sqlcon.HandleError(p.QueryWithNetwork(ctx).Where("verifier=?", verifier).First(&lr))
if err != nil {
return nil, err
}
return &lr, nil
}
func (p *Persister) FlushInactiveLoginConsentRequests(ctx context.Context, notAfter time.Time, limit int, batchSize int) error {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.FlushInactiveLoginConsentRequests")
defer span.End()
/* #nosec G201 table is static */
var f flow.Flow
// The value of notAfter should be the minimum between input parameter and request max expire based on its configured age
requestMaxExpire := time.Now().Add(-p.config.ConsentRequestMaxAge(ctx))
if requestMaxExpire.Before(notAfter) {
notAfter = requestMaxExpire
}
challenges := []string{}
queryFormat := `
SELECT login_challenge
FROM hydra_oauth2_flow
WHERE (
(state != ?)
OR (login_error IS NOT NULL AND login_error <> '{}' AND login_error <> '')
OR (consent_error IS NOT NULL AND consent_error <> '{}' AND consent_error <> '')
)
AND requested_at < ?
AND nid = ?
ORDER BY login_challenge
LIMIT %[1]d
`
// Select up to [limit] flows that can be safely deleted, i.e. flows that meet
// the following criteria:
// - flow.state is anything between FlowStateLoginInitialized and FlowStateConsentUnused (unhandled)
// - flow.login_error has valid error (login rejected)
// - flow.consent_error has valid error (consent rejected)
// AND timed-out
// - flow.requested_at < minimum of ttl.login_consent_request and notAfter
q := p.Connection(ctx).RawQuery(fmt.Sprintf(queryFormat, limit), flow.FlowStateConsentUsed, notAfter, p.NetworkID(ctx))
if err := q.All(&challenges); err == sql.ErrNoRows {
return errors.Wrap(fosite.ErrNotFound, "")
}
// Delete in batch consent requests and their references in cascade
for i := 0; i < len(challenges); i += batchSize {
j := i + batchSize
if j > len(challenges) {
j = len(challenges)
}
q := p.Connection(ctx).RawQuery(
fmt.Sprintf("DELETE FROM %s WHERE login_challenge in (?) AND nid = ?", (&f).TableName()),
challenges[i:j],
p.NetworkID(ctx),
)
if err := q.Exec(); err != nil {
return sqlcon.HandleError(err)
}
}
return nil
} |
Go | hydra/persistence/sql/persister_grant_jwk.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package sql
import (
"context"
"strings"
"time"
"github.com/pkg/errors"
"github.com/go-jose/go-jose/v3"
"github.com/gobuffalo/pop/v6"
"github.com/ory/hydra/v2/oauth2/trust"
"github.com/ory/x/otelx"
"github.com/ory/x/stringsx"
"github.com/ory/x/sqlcon"
)
var _ trust.GrantManager = &Persister{}
func (p *Persister) CreateGrant(ctx context.Context, g trust.Grant, publicKey jose.JSONWebKey) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.CreateGrant")
defer otelx.End(span, &err)
return p.transaction(ctx, func(ctx context.Context, c *pop.Connection) error {
// add key, if it doesn't exist
if _, err := p.GetKey(ctx, g.PublicKey.Set, g.PublicKey.KeyID); err != nil {
if !errors.Is(err, sqlcon.ErrNoRows) {
return sqlcon.HandleError(err)
}
if err = p.AddKey(ctx, g.PublicKey.Set, &publicKey); err != nil {
return sqlcon.HandleError(err)
}
}
data := p.sqlDataFromJWTGrant(g)
return sqlcon.HandleError(p.CreateWithNetwork(ctx, &data))
})
}
func (p *Persister) GetConcreteGrant(ctx context.Context, id string) (_ trust.Grant, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetConcreteGrant")
defer otelx.End(span, &err)
var data trust.SQLData
if err := p.QueryWithNetwork(ctx).Where("id = ?", id).First(&data); err != nil {
return trust.Grant{}, sqlcon.HandleError(err)
}
return p.jwtGrantFromSQlData(data), nil
}
func (p *Persister) DeleteGrant(ctx context.Context, id string) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.DeleteGrant")
defer otelx.End(span, &err)
return p.transaction(ctx, func(ctx context.Context, c *pop.Connection) error {
grant, err := p.GetConcreteGrant(ctx, id)
if err != nil {
return sqlcon.HandleError(err)
}
if err := p.QueryWithNetwork(ctx).Where("id = ?", grant.ID).Delete(&trust.SQLData{}); err != nil {
return sqlcon.HandleError(err)
}
return p.DeleteKey(ctx, grant.PublicKey.Set, grant.PublicKey.KeyID)
})
}
func (p *Persister) GetGrants(ctx context.Context, limit, offset int, optionalIssuer string) (_ []trust.Grant, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetGrants")
defer otelx.End(span, &err)
grantsData := make([]trust.SQLData, 0)
query := p.QueryWithNetwork(ctx).
Paginate(offset/limit+1, limit).
Order("id")
if optionalIssuer != "" {
query = query.Where("issuer = ?", optionalIssuer)
}
if err := query.All(&grantsData); err != nil {
return nil, sqlcon.HandleError(err)
}
grants := make([]trust.Grant, 0, len(grantsData))
for _, data := range grantsData {
grants = append(grants, p.jwtGrantFromSQlData(data))
}
return grants, nil
}
func (p *Persister) CountGrants(ctx context.Context) (n int, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.CountGrants")
defer otelx.End(span, &err)
n, err = p.QueryWithNetwork(ctx).
Count(&trust.SQLData{})
return n, sqlcon.HandleError(err)
}
func (p *Persister) GetPublicKey(ctx context.Context, issuer string, subject string, keyId string) (_ *jose.JSONWebKey, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetPublicKey")
defer otelx.End(span, &err)
var data trust.SQLData
query := p.QueryWithNetwork(ctx).
Where("issuer = ?", issuer).
Where("(subject = ? OR allow_any_subject IS TRUE)", subject).
Where("key_id = ?", keyId).
Where("nid = ?", p.NetworkID(ctx))
if err := query.First(&data); err != nil {
return nil, sqlcon.HandleError(err)
}
keySet, err := p.GetKey(ctx, data.KeySet, keyId)
if err != nil {
return nil, err
}
return &keySet.Keys[0], nil
}
func (p *Persister) GetPublicKeys(ctx context.Context, issuer string, subject string) (_ *jose.JSONWebKeySet, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetPublicKeys")
defer otelx.End(span, &err)
grantsData := make([]trust.SQLData, 0)
query := p.QueryWithNetwork(ctx).
Where("issuer = ?", issuer).
Where("(subject = ? OR allow_any_subject IS TRUE)", subject).
Where("nid = ?", p.NetworkID(ctx))
if err := query.All(&grantsData); err != nil {
return nil, sqlcon.HandleError(err)
}
if len(grantsData) == 0 {
return &jose.JSONWebKeySet{}, nil
}
// because keys must be grouped by issuer, we can retrieve set name from first grant
keySet, err := p.GetKeySet(ctx, grantsData[0].KeySet)
if err != nil {
return nil, err
}
// find keys, that belong to grants
filteredKeySet := &jose.JSONWebKeySet{}
for _, data := range grantsData {
if keys := keySet.Key(data.KeyID); len(keys) > 0 {
filteredKeySet.Keys = append(filteredKeySet.Keys, keys...)
}
}
return filteredKeySet, nil
}
func (p *Persister) GetPublicKeyScopes(ctx context.Context, issuer string, subject string, keyId string) (_ []string, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetPublicKeyScopes")
defer otelx.End(span, &err)
var data trust.SQLData
query := p.QueryWithNetwork(ctx).
Where("issuer = ?", issuer).
Where("(subject = ? OR allow_any_subject IS TRUE)", subject).
Where("key_id = ?", keyId).
Where("nid = ?", p.NetworkID(ctx))
if err := query.First(&data); err != nil {
return nil, sqlcon.HandleError(err)
}
return p.jwtGrantFromSQlData(data).Scope, nil
}
func (p *Persister) IsJWTUsed(ctx context.Context, jti string) (ok bool, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.IsJWTUsed")
defer otelx.End(span, &err)
err = p.ClientAssertionJWTValid(ctx, jti)
if err != nil {
return true, nil
}
return false, nil
}
func (p *Persister) MarkJWTUsedForTime(ctx context.Context, jti string, exp time.Time) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.MarkJWTUsedForTime")
defer otelx.End(span, &err)
return p.SetClientAssertionJWT(ctx, jti, exp)
}
func (p *Persister) sqlDataFromJWTGrant(g trust.Grant) trust.SQLData {
return trust.SQLData{
ID: g.ID,
Issuer: g.Issuer,
Subject: g.Subject,
AllowAnySubject: g.AllowAnySubject,
Scope: strings.Join(g.Scope, "|"),
KeySet: g.PublicKey.Set,
KeyID: g.PublicKey.KeyID,
CreatedAt: g.CreatedAt,
ExpiresAt: g.ExpiresAt,
}
}
func (p *Persister) jwtGrantFromSQlData(data trust.SQLData) trust.Grant {
return trust.Grant{
ID: data.ID,
Issuer: data.Issuer,
Subject: data.Subject,
AllowAnySubject: data.AllowAnySubject,
Scope: stringsx.Splitx(data.Scope, "|"),
PublicKey: trust.PublicKey{
Set: data.KeySet,
KeyID: data.KeyID,
},
CreatedAt: data.CreatedAt,
ExpiresAt: data.ExpiresAt,
}
}
func (p *Persister) FlushInactiveGrants(ctx context.Context, notAfter time.Time, _ int, _ int) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.FlushInactiveGrants")
defer otelx.End(span, &err)
deleteUntil := time.Now().UTC()
if deleteUntil.After(notAfter) {
deleteUntil = notAfter
}
return sqlcon.HandleError(p.QueryWithNetwork(ctx).Where("expires_at < ?", deleteUntil).Delete(&trust.SQLData{}))
} |
Go | hydra/persistence/sql/persister_jwk.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package sql
import (
"context"
"encoding/json"
"github.com/go-jose/go-jose/v3"
"github.com/gobuffalo/pop/v6"
"github.com/ory/x/errorsx"
"github.com/pkg/errors"
"github.com/ory/hydra/v2/jwk"
"github.com/ory/hydra/v2/x"
"github.com/ory/x/sqlcon"
)
var _ jwk.Manager = &Persister{}
func (p *Persister) GenerateAndPersistKeySet(ctx context.Context, set, kid, alg, use string) (*jose.JSONWebKeySet, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GenerateAndPersistKey")
defer span.End()
keys, err := jwk.GenerateJWK(ctx, jose.SignatureAlgorithm(alg), kid, use)
if err != nil {
return nil, errors.Wrapf(jwk.ErrUnsupportedKeyAlgorithm, "%s", err)
}
err = p.AddKeySet(ctx, set, keys)
if err != nil {
return nil, err
}
return keys, nil
}
func (p *Persister) AddKey(ctx context.Context, set string, key *jose.JSONWebKey) error {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.AddKey")
defer span.End()
out, err := json.Marshal(key)
if err != nil {
return errorsx.WithStack(err)
}
encrypted, err := p.r.KeyCipher().Encrypt(ctx, out, nil)
if err != nil {
return errorsx.WithStack(err)
}
return sqlcon.HandleError(p.CreateWithNetwork(ctx, &jwk.SQLData{
Set: set,
KID: key.KeyID,
Version: 0,
Key: encrypted,
}))
}
func (p *Persister) AddKeySet(ctx context.Context, set string, keys *jose.JSONWebKeySet) error {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.AddKey")
defer span.End()
return p.transaction(ctx, func(ctx context.Context, c *pop.Connection) error {
for _, key := range keys.Keys {
out, err := json.Marshal(key)
if err != nil {
return errorsx.WithStack(err)
}
encrypted, err := p.r.KeyCipher().Encrypt(ctx, out, nil)
if err != nil {
return err
}
if err := p.CreateWithNetwork(ctx, &jwk.SQLData{
Set: set,
KID: key.KeyID,
Version: 0,
Key: encrypted,
}); err != nil {
return sqlcon.HandleError(err)
}
}
return nil
})
}
// UpdateKey updates or creates the key.
func (p *Persister) UpdateKey(ctx context.Context, set string, key *jose.JSONWebKey) error {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.UpdateKey")
defer span.End()
return p.transaction(ctx, func(ctx context.Context, c *pop.Connection) error {
if err := p.DeleteKey(ctx, set, key.KeyID); err != nil {
return err
}
if err := p.AddKey(ctx, set, key); err != nil {
return err
}
return nil
})
}
// UpdateKeySet updates or creates the key set.
func (p *Persister) UpdateKeySet(ctx context.Context, set string, keySet *jose.JSONWebKeySet) error {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.UpdateKeySet")
defer span.End()
return p.transaction(ctx, func(ctx context.Context, c *pop.Connection) error {
if err := p.DeleteKeySet(ctx, set); err != nil {
return err
}
if err := p.AddKeySet(ctx, set, keySet); err != nil {
return err
}
return nil
})
}
func (p *Persister) GetKey(ctx context.Context, set, kid string) (*jose.JSONWebKeySet, error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetKey")
defer span.End()
var j jwk.SQLData
if err := p.QueryWithNetwork(ctx).
Where("sid = ? AND kid = ?", set, kid).
Order("created_at DESC").
First(&j); err != nil {
return nil, sqlcon.HandleError(err)
}
key, err := p.r.KeyCipher().Decrypt(ctx, j.Key, nil)
if err != nil {
return nil, errorsx.WithStack(err)
}
var c jose.JSONWebKey
if err := json.Unmarshal(key, &c); err != nil {
return nil, errorsx.WithStack(err)
}
return &jose.JSONWebKeySet{
Keys: []jose.JSONWebKey{c},
}, nil
}
func (p *Persister) GetKeySet(ctx context.Context, set string) (keys *jose.JSONWebKeySet, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetKeySet")
defer span.End()
var js []jwk.SQLData
if err := p.QueryWithNetwork(ctx).
Where("sid = ?", set).
Order("created_at DESC").
All(&js); err != nil {
return nil, sqlcon.HandleError(err)
}
if len(js) == 0 {
return nil, errors.Wrap(x.ErrNotFound, "")
}
keys = &jose.JSONWebKeySet{Keys: []jose.JSONWebKey{}}
for _, d := range js {
key, err := p.r.KeyCipher().Decrypt(ctx, d.Key, nil)
if err != nil {
return nil, errorsx.WithStack(err)
}
var c jose.JSONWebKey
if err := json.Unmarshal(key, &c); err != nil {
return nil, errorsx.WithStack(err)
}
keys.Keys = append(keys.Keys, c)
}
if len(keys.Keys) == 0 {
return nil, errorsx.WithStack(x.ErrNotFound)
}
return keys, nil
}
func (p *Persister) DeleteKey(ctx context.Context, set, kid string) error {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.DeleteKey")
defer span.End()
err := p.QueryWithNetwork(ctx).Where("sid=? AND kid=?", set, kid).Delete(&jwk.SQLData{})
return sqlcon.HandleError(err)
}
func (p *Persister) DeleteKeySet(ctx context.Context, set string) error {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.DeleteKeySet")
defer span.End()
err := p.QueryWithNetwork(ctx).Where("sid=?", set).Delete(&jwk.SQLData{})
return sqlcon.HandleError(err)
} |
Go | hydra/persistence/sql/persister_migration.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package sql
import (
"context"
"embed"
"fmt"
"strconv"
"strings"
"time"
"github.com/gobuffalo/pop/v6"
"github.com/ory/x/popx"
"github.com/ory/x/errorsx"
"github.com/ory/x/sqlcon"
)
//go:embed migrations/*.sql
var migrations embed.FS
func (p *Persister) MigrationStatus(ctx context.Context) (popx.MigrationStatuses, error) {
if p.mbs != nil {
return p.mbs, nil
}
status, err := p.mb.Status(ctx)
if err != nil {
return nil, err
}
if !status.HasPending() {
p.mbs = status
}
return status, nil
}
func (p *Persister) MigrateDown(ctx context.Context, steps int) error {
return errorsx.WithStack(p.mb.Down(ctx, steps))
}
func (p *Persister) MigrateUp(ctx context.Context) error {
if err := p.migrateOldMigrationTables(); err != nil {
return err
}
return errorsx.WithStack(p.mb.Up(ctx))
}
func (p *Persister) MigrateUpTo(ctx context.Context, steps int) (int, error) {
if err := p.migrateOldMigrationTables(); err != nil {
return 0, err
}
n, err := p.mb.UpTo(ctx, steps)
return n, errorsx.WithStack(err)
}
func (p *Persister) PrepareMigration(_ context.Context) error {
return p.migrateOldMigrationTables()
}
type oldTableName string
const (
clientMigrationTableName oldTableName = "hydra_client_migration"
jwkMigrationTableName oldTableName = "hydra_jwk_migration"
consentMigrationTableName oldTableName = "hydra_oauth2_authentication_consent_migration"
oauth2MigrationTableName oldTableName = "hydra_oauth2_migration"
)
// this type is copied from sql-migrate to remove the dependency
type OldMigrationRecord struct {
ID string `db:"id"`
AppliedAt time.Time `db:"applied_at"`
}
// this function is idempotent
func (p *Persister) migrateOldMigrationTables() error {
if err := p.conn.RawQuery(fmt.Sprintf("SELECT * FROM %s", clientMigrationTableName)).Exec(); err != nil {
// assume there are no old migration tables => done
return nil
}
if err := pop.CreateSchemaMigrations(p.conn); err != nil {
return errorsx.WithStack(err)
}
// in this order the migrations only depend on already done ones
for i, table := range []oldTableName{clientMigrationTableName, jwkMigrationTableName, consentMigrationTableName, oauth2MigrationTableName} {
// If table does not exist, we will skip it. Previously, we created a stub table here which
// caused the cached statements to fail, see:
//
// https://github.com/flynn/flynn/pull/2306/files
// https://github.com/jackc/pgx/issues/110
// https://github.com/flynn/flynn/issues/2235
// get old migrations
var migrations []OldMigrationRecord
/* #nosec G201 table is static */
if err := p.conn.RawQuery(fmt.Sprintf("SELECT * FROM %s", table)).All(&migrations); err != nil {
if strings.Contains(err.Error(), string(table)) {
continue
}
return err
}
// translate migrations
for _, m := range migrations {
// mark the migration as run for fizz
// fizz standard version pattern: YYYYMMDDhhmmss
migrationNumber, err := strconv.ParseInt(m.ID, 10, 0)
if err != nil {
return errorsx.WithStack(err)
}
/* #nosec G201 - i is static (0..3) and migrationNumber is from the database */
if err := p.conn.RawQuery(
fmt.Sprintf("INSERT INTO schema_migration (version) VALUES ('2019%02d%08d')", i+1, migrationNumber)).
Exec(); err != nil {
return errorsx.WithStack(err)
}
}
// delete old migration table
if err := p.conn.RawQuery(fmt.Sprintf("DROP TABLE %s", table)).Exec(); err != nil {
return sqlcon.HandleError(err)
}
}
return nil
} |
Go | hydra/persistence/sql/persister_nid_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package sql_test
import (
"context"
"database/sql"
"encoding/json"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/ory/hydra/v2/persistence"
"github.com/ory/x/uuidx"
"github.com/ory/x/assertx"
"github.com/go-jose/go-jose/v3"
"github.com/gofrs/uuid"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/ory/fosite"
"github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/consent"
"github.com/ory/hydra/v2/driver"
"github.com/ory/hydra/v2/flow"
"github.com/ory/hydra/v2/internal"
"github.com/ory/hydra/v2/jwk"
"github.com/ory/hydra/v2/oauth2"
"github.com/ory/hydra/v2/oauth2/trust"
persistencesql "github.com/ory/hydra/v2/persistence/sql"
"github.com/ory/hydra/v2/x"
"github.com/ory/x/contextx"
"github.com/ory/x/dbal"
"github.com/ory/x/networkx"
"github.com/ory/x/sqlxx"
)
type PersisterTestSuite struct {
suite.Suite
registries map[string]driver.Registry
t1 context.Context
t2 context.Context
t1NID uuid.UUID
t2NID uuid.UUID
}
var _ interface {
suite.SetupAllSuite
suite.TearDownTestSuite
} = (*PersisterTestSuite)(nil)
func (s *PersisterTestSuite) SetupSuite() {
s.registries = map[string]driver.Registry{
"memory": internal.NewRegistrySQLFromURL(s.T(), dbal.NewSQLiteTestDatabase(s.T()), true, &contextx.Default{}),
}
if !testing.Short() {
s.registries["postgres"], s.registries["mysql"], s.registries["cockroach"], _ = internal.ConnectDatabases(s.T(), true, &contextx.Default{})
}
s.t1NID, s.t2NID = uuid.Must(uuid.NewV4()), uuid.Must(uuid.NewV4())
s.t1 = contextx.SetNIDContext(context.Background(), s.t1NID)
s.t2 = contextx.SetNIDContext(context.Background(), s.t2NID)
for _, r := range s.registries {
require.NoError(s.T(), r.Persister().Connection(context.Background()).Create(&networkx.Network{ID: s.t1NID}))
require.NoError(s.T(), r.Persister().Connection(context.Background()).Create(&networkx.Network{ID: s.t2NID}))
r.WithContextualizer(&contextx.TestContextualizer{})
}
}
func (s *PersisterTestSuite) TearDownTest() {
for _, r := range s.registries {
r.WithContextualizer(&contextx.TestContextualizer{})
x.DeleteHydraRows(s.T(), r.Persister().Connection(context.Background()))
}
}
func (s *PersisterTestSuite) TestAcceptLogoutRequest() {
t := s.T()
lr := newLogoutRequest()
for k, r := range s.registries {
t.Run("dialect="+k, func(*testing.T) {
require.NoError(t, r.ConsentManager().CreateLogoutRequest(s.t1, lr))
expected, err := r.ConsentManager().GetLogoutRequest(s.t1, lr.ID)
require.NoError(t, err)
require.Equal(t, false, expected.Accepted)
lrAccepted, err := r.ConsentManager().AcceptLogoutRequest(s.t2, lr.ID)
require.Error(t, err)
require.Equal(t, &flow.LogoutRequest{}, lrAccepted)
actual, err := r.ConsentManager().GetLogoutRequest(s.t1, lr.ID)
require.NoError(t, err)
require.Equal(t, expected, actual)
})
}
}
func (s *PersisterTestSuite) TestAddKeyGetKeyDeleteKey() {
t := s.T()
key := newKey("test-ks", "test")
for k, r := range s.registries {
t.Run("dialect="+k, func(*testing.T) {
ks := "key-set"
require.NoError(t, r.Persister().AddKey(s.t1, ks, &key))
actual, err := r.Persister().GetKey(s.t2, ks, key.KeyID)
require.Error(t, err)
require.Equal(t, (*jose.JSONWebKeySet)(nil), actual)
actual, err = r.Persister().GetKey(s.t1, ks, key.KeyID)
require.NoError(t, err)
assertx.EqualAsJSON(t, &jose.JSONWebKeySet{Keys: []jose.JSONWebKey{key}}, actual)
r.Persister().DeleteKey(s.t2, ks, key.KeyID)
_, err = r.Persister().GetKey(s.t1, ks, key.KeyID)
require.NoError(t, err)
r.Persister().DeleteKey(s.t1, ks, key.KeyID)
_, err = r.Persister().GetKey(s.t1, ks, key.KeyID)
require.Error(t, err)
})
}
}
func (s *PersisterTestSuite) TestAddKeySetGetKeySetDeleteKeySet() {
t := s.T()
ks := newKeySet("test-ks", "test")
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
ksID := "key-set"
r.Persister().AddKeySet(s.t1, ksID, ks)
actual, err := r.Persister().GetKeySet(s.t2, ksID)
require.Error(t, err)
require.Equal(t, (*jose.JSONWebKeySet)(nil), actual)
actual, err = r.Persister().GetKeySet(s.t1, ksID)
require.NoError(t, err)
requireKeySetEqual(t, ks, actual)
r.Persister().DeleteKeySet(s.t2, ksID)
_, err = r.Persister().GetKeySet(s.t1, ksID)
require.NoError(t, err)
r.Persister().DeleteKeySet(s.t1, ksID)
_, err = r.Persister().GetKeySet(s.t1, ksID)
require.Error(t, err)
})
}
}
func (s *PersisterTestSuite) TestAuthenticate() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id", Secret: "secret"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
actual, err := r.Persister().Authenticate(s.t2, "client-id", []byte("secret"))
require.Error(t, err)
require.Nil(t, actual)
actual, err = r.Persister().Authenticate(s.t1, "client-id", []byte("secret"))
require.NoError(t, err)
require.NotNil(t, actual)
})
}
}
func (s *PersisterTestSuite) TestClientAssertionJWTValid() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
jti := oauth2.NewBlacklistedJTI(uuid.Must(uuid.NewV4()).String(), time.Now().Add(24*time.Hour))
require.NoError(t, r.Persister().SetClientAssertionJWT(s.t1, jti.JTI, jti.Expiry))
require.NoError(t, r.Persister().ClientAssertionJWTValid(s.t2, jti.JTI))
require.Error(t, r.Persister().ClientAssertionJWTValid(s.t1, jti.JTI))
})
}
}
func (s *PersisterTestSuite) TestConfirmLoginSession() {
t := s.T()
ls := newLoginSession()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
require.NoError(t, r.Persister().CreateLoginSession(s.t1, ls))
// Expects the login session to be confirmed in the correct context.
require.NoError(t, r.Persister().ConfirmLoginSession(s.t1, ls, ls.ID, time.Now().UTC(), ls.Subject, !ls.Remember))
actual := &flow.LoginSession{}
require.NoError(t, r.Persister().Connection(context.Background()).Find(actual, ls.ID))
exp, _ := json.Marshal(ls)
act, _ := json.Marshal(actual)
require.JSONEq(t, string(exp), string(act))
// Can't find the login session in the wrong context.
require.ErrorIs(t,
r.Persister().ConfirmLoginSession(s.t2, ls, ls.ID, time.Now().UTC(), ls.Subject, !ls.Remember),
x.ErrNotFound,
)
})
}
}
func (s *PersisterTestSuite) TestCreateSession() {
t := s.T()
ls := newLoginSession()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
persistLoginSession(s.t1, t, r.Persister(), ls)
actual := &flow.LoginSession{}
require.NoError(t, r.Persister().Connection(context.Background()).Find(actual, ls.ID))
require.Equal(t, s.t1NID, actual.NID)
ls.NID = actual.NID
require.Equal(t, ls, actual)
})
}
}
func (s *PersisterTestSuite) TestCountClients() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
count, err := r.Persister().CountClients(s.t1)
require.NoError(t, err)
require.Equal(t, 0, count)
count, err = r.Persister().CountClients(s.t2)
require.NoError(t, err)
require.Equal(t, 0, count)
require.NoError(t, r.Persister().CreateClient(s.t1, newClient()))
count, err = r.Persister().CountClients(s.t1)
require.NoError(t, err)
require.Equal(t, 1, count)
count, err = r.Persister().CountClients(s.t2)
require.NoError(t, err)
require.Equal(t, 0, count)
})
}
}
func (s *PersisterTestSuite) TestCountGrants() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
count, err := r.Persister().CountGrants(s.t1)
require.NoError(t, err)
require.Equal(t, 0, count)
count, err = r.Persister().CountGrants(s.t2)
require.NoError(t, err)
require.Equal(t, 0, count)
keySet := uuid.Must(uuid.NewV4()).String()
publicKey := newKey(keySet, "use")
grant := newGrant(keySet, publicKey.KeyID)
require.NoError(t, r.Persister().AddKey(s.t1, keySet, &publicKey))
require.NoError(t, r.Persister().CreateGrant(s.t1, grant, publicKey))
count, err = r.Persister().CountGrants(s.t1)
require.NoError(t, err)
require.Equal(t, 1, count)
count, err = r.Persister().CountGrants(s.t2)
require.NoError(t, err)
require.Equal(t, 0, count)
})
}
}
func (s *PersisterTestSuite) TestCountSubjectsGrantedConsentRequests() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
sub := uuid.Must(uuid.NewV4()).String()
count, err := r.Persister().CountSubjectsGrantedConsentRequests(s.t1, sub)
require.NoError(t, err)
require.Equal(t, 0, count)
count, err = r.Persister().CountSubjectsGrantedConsentRequests(s.t2, sub)
require.NoError(t, err)
require.Equal(t, 0, count)
sessionID := uuid.Must(uuid.NewV4()).String()
persistLoginSession(s.t1, t, r.Persister(), &flow.LoginSession{ID: sessionID})
client := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
f := newFlow(s.t1NID, client.LegacyClientID, sub, sqlxx.NullString(sessionID))
f.ConsentSkip = false
f.ConsentError = &flow.RequestDeniedError{}
f.State = flow.FlowStateConsentUnused
require.NoError(t, r.Persister().Connection(context.Background()).Create(f))
count, err = r.Persister().CountSubjectsGrantedConsentRequests(s.t1, sub)
require.NoError(t, err)
require.Equal(t, 1, count)
count, err = r.Persister().CountSubjectsGrantedConsentRequests(s.t2, sub)
require.NoError(t, err)
require.Equal(t, 0, count)
})
}
}
func (s *PersisterTestSuite) TestCreateAccessTokenSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
c1 := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, c1))
c2 := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t2, c2))
sig := uuid.Must(uuid.NewV4()).String()
fr := fosite.NewRequest()
fr.Client = &fosite.DefaultClient{ID: c1.LegacyClientID}
require.NoError(t, r.Persister().CreateAccessTokenSession(s.t1, sig, fr))
actual := persistencesql.OAuth2RequestSQL{Table: "access"}
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, persistencesql.SignatureHash(sig)))
require.Equal(t, s.t1NID, actual.NID)
})
}
}
func (s *PersisterTestSuite) TestCreateAuthorizeCodeSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
c1 := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, c1))
c2 := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t2, c2))
sig := uuid.Must(uuid.NewV4()).String()
fr := fosite.NewRequest()
fr.Client = &fosite.DefaultClient{ID: c1.LegacyClientID}
require.NoError(t, r.Persister().CreateAuthorizeCodeSession(s.t1, sig, fr))
actual := persistencesql.OAuth2RequestSQL{Table: "code"}
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, sig))
require.Equal(t, s.t1NID, actual.NID)
})
}
}
func (s *PersisterTestSuite) TestCreateClient() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
expected := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, expected))
actual := client.Client{}
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, expected.ID))
require.Equal(t, s.t1NID, actual.NID)
})
}
}
func (s *PersisterTestSuite) TestCreateConsentRequest() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
sessionID := uuid.Must(uuid.NewV4()).String()
client := &client.Client{LegacyClientID: "client-id"}
f := newFlow(s.t1NID, client.LegacyClientID, "sub", sqlxx.NullString(sessionID))
persistLoginSession(s.t1, t, r.Persister(), &flow.LoginSession{ID: sessionID})
require.NoError(t, r.Persister().CreateClient(s.t1, client))
require.NoError(t, r.Persister().Connection(context.Background()).Create(f))
req := &flow.OAuth2ConsentRequest{
ID: "consent-request-id",
LoginChallenge: sqlxx.NullString(f.ID),
Skip: false,
Verifier: "verifier",
CSRF: "csrf",
}
require.NoError(t, r.Persister().CreateConsentRequest(s.t1, f, req))
actual := flow.Flow{}
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, f.ID))
require.Equal(t, s.t1NID, actual.NID)
})
}
}
func (s *PersisterTestSuite) TestCreateForcedObfuscatedLoginSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
session := &consent.ForcedObfuscatedLoginSession{ClientID: client.LegacyClientID}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
require.NoError(t, r.Persister().CreateForcedObfuscatedLoginSession(s.t1, session))
actual, err := r.Persister().GetForcedObfuscatedLoginSession(s.t1, client.LegacyClientID, "")
require.NoError(t, err)
require.Equal(t, s.t1NID, actual.NID)
})
}
}
func (s *PersisterTestSuite) TestCreateGrant() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
ks := newKeySet("ks-id", "use")
grant := trust.Grant{
ID: uuid.Must(uuid.NewV4()).String(),
ExpiresAt: time.Now().Add(time.Hour),
PublicKey: trust.PublicKey{Set: "ks-id", KeyID: ks.Keys[0].KeyID},
}
require.NoError(t, r.Persister().AddKeySet(s.t1, "ks-id", ks))
require.NoError(t, r.Persister().CreateGrant(s.t1, grant, ks.Keys[0]))
actual := trust.SQLData{}
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, grant.ID))
require.Equal(t, s.t1NID, actual.NID)
})
}
}
func (s *PersisterTestSuite) TestCreateLoginRequest() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
lr := flow.LoginRequest{ID: "lr-id", ClientID: client.LegacyClientID, RequestedAt: time.Now()}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
f, err := r.ConsentManager().CreateLoginRequest(s.t1, &lr)
require.NoError(t, err)
require.Equal(t, s.t1NID, f.NID)
})
}
}
func (s *PersisterTestSuite) TestCreateLoginSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
ls := flow.LoginSession{ID: uuid.Must(uuid.NewV4()).String(), Remember: true}
require.NoError(t, r.Persister().CreateLoginSession(s.t1, &ls))
actual, err := r.Persister().GetRememberedLoginSession(s.t1, &ls, ls.ID)
require.NoError(t, err)
require.Equal(t, s.t1NID, actual.NID)
})
}
}
func (s *PersisterTestSuite) TestCreateLogoutRequest() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
lr := flow.LogoutRequest{
// TODO there is not FK for SessionID so we don't need it here; TODO make sure the missing FK is intentional
ID: uuid.Must(uuid.NewV4()).String(),
ClientID: sql.NullString{Valid: true, String: client.LegacyClientID},
}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
require.NoError(t, r.Persister().CreateLogoutRequest(s.t1, &lr))
actual, err := r.Persister().GetLogoutRequest(s.t1, lr.ID)
require.NoError(t, err)
require.Equal(t, s.t1NID, actual.NID)
})
}
}
func (s *PersisterTestSuite) TestCreateOpenIDConnectSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
request := fosite.NewRequest()
request.Client = &fosite.DefaultClient{ID: "client-id"}
authorizeCode := uuid.Must(uuid.NewV4()).String()
require.NoError(t, r.Persister().CreateOpenIDConnectSession(s.t1, authorizeCode, request))
actual := persistencesql.OAuth2RequestSQL{Table: "oidc"}
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, authorizeCode))
require.Equal(t, s.t1NID, actual.NID)
})
}
}
func (s *PersisterTestSuite) TestCreatePKCERequestSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
request := fosite.NewRequest()
request.Client = &fosite.DefaultClient{ID: "client-id"}
authorizeCode := uuid.Must(uuid.NewV4()).String()
actual := persistencesql.OAuth2RequestSQL{Table: "pkce"}
require.Error(t, r.Persister().Connection(context.Background()).Find(&actual, authorizeCode))
require.NoError(t, r.Persister().CreatePKCERequestSession(s.t1, authorizeCode, request))
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, authorizeCode))
require.Equal(t, s.t1NID, actual.NID)
})
}
}
func (s *PersisterTestSuite) TestCreateRefreshTokenSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
request := fosite.NewRequest()
request.Client = &fosite.DefaultClient{ID: "client-id"}
authorizeCode := uuid.Must(uuid.NewV4()).String()
actual := persistencesql.OAuth2RequestSQL{Table: "refresh"}
require.Error(t, r.Persister().Connection(context.Background()).Find(&actual, authorizeCode))
require.NoError(t, r.Persister().CreateRefreshTokenSession(s.t1, authorizeCode, request))
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, authorizeCode))
require.Equal(t, s.t1NID, actual.NID)
})
}
}
func (s *PersisterTestSuite) TestCreateWithNetwork() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
expected := &client.Client{LegacyClientID: "client-id"}
store, ok := r.OAuth2Storage().(*persistencesql.Persister)
if !ok {
t.Fatal("type assertion failed")
}
store.CreateWithNetwork(s.t1, expected)
actual := &client.Client{}
require.NoError(t, r.Persister().Connection(context.Background()).Where("id = ?", expected.LegacyClientID).First(actual))
require.Equal(t, s.t1NID, actual.NID)
})
}
}
func (s *PersisterTestSuite) DeleteAccessTokenSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
sig := uuid.Must(uuid.NewV4()).String()
fr := fosite.NewRequest()
fr.Client = &fosite.DefaultClient{ID: client.LegacyClientID}
require.NoError(t, r.Persister().CreateAccessTokenSession(s.t1, sig, fr))
require.NoError(t, r.Persister().DeleteAccessTokenSession(s.t2, sig))
actual := persistencesql.OAuth2RequestSQL{Table: "access"}
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, persistencesql.SignatureHash(sig)))
require.Equal(t, s.t1NID, actual.NID)
require.NoError(t, r.Persister().DeleteAccessTokenSession(s.t1, sig))
require.Error(t, r.Persister().Connection(context.Background()).Find(&actual, persistencesql.SignatureHash(sig)))
})
}
}
func (s *PersisterTestSuite) TestDeleteAccessTokens() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
sig := uuid.Must(uuid.NewV4()).String()
fr := fosite.NewRequest()
fr.Client = &fosite.DefaultClient{ID: client.LegacyClientID}
require.NoError(t, r.Persister().CreateAccessTokenSession(s.t1, sig, fr))
require.NoError(t, r.Persister().DeleteAccessTokens(s.t2, client.LegacyClientID))
actual := persistencesql.OAuth2RequestSQL{Table: "access"}
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, persistencesql.SignatureHash(sig)))
require.Equal(t, s.t1NID, actual.NID)
require.NoError(t, r.Persister().DeleteAccessTokens(s.t1, client.LegacyClientID))
require.Error(t, r.Persister().Connection(context.Background()).Find(&actual, persistencesql.SignatureHash(sig)))
})
}
}
func (s *PersisterTestSuite) TestDeleteClient() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
c := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, c))
actual := client.Client{}
require.Error(t, r.Persister().DeleteClient(s.t2, c.LegacyClientID))
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, c.ID))
require.NoError(t, r.Persister().DeleteClient(s.t1, c.LegacyClientID))
require.Error(t, r.Persister().Connection(context.Background()).Find(&actual, c.ID))
})
}
}
func (s *PersisterTestSuite) TestDeleteGrant() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
ks := newKeySet("ks-id", "use")
grant := trust.Grant{
ID: uuid.Must(uuid.NewV4()).String(),
ExpiresAt: time.Now().Add(time.Hour),
PublicKey: trust.PublicKey{Set: "ks-id", KeyID: ks.Keys[0].KeyID},
}
require.NoError(t, r.Persister().AddKeySet(s.t1, "ks-id", ks))
require.NoError(t, r.Persister().CreateGrant(s.t1, grant, ks.Keys[0]))
actual := trust.SQLData{}
require.Error(t, r.Persister().DeleteGrant(s.t2, grant.ID))
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, grant.ID))
require.NoError(t, r.Persister().DeleteGrant(s.t1, grant.ID))
require.Error(t, r.Persister().Connection(context.Background()).Find(&actual, grant.ID))
})
}
}
func (s *PersisterTestSuite) TestDeleteLoginSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
ls := flow.LoginSession{
ID: uuid.Must(uuid.NewV4()).String(),
Remember: true,
IdentityProviderSessionID: sqlxx.NullString(uuid.Must(uuid.NewV4()).String()),
}
persistLoginSession(s.t1, t, r.Persister(), &ls)
deletedLS, err := r.Persister().DeleteLoginSession(s.t2, ls.ID)
require.Error(t, err)
assert.Nil(t, deletedLS)
_, err = r.Persister().GetRememberedLoginSession(s.t1, nil, ls.ID)
require.NoError(t, err)
deletedLS, err = r.Persister().DeleteLoginSession(s.t1, ls.ID)
require.NoError(t, err)
assert.Equal(t, ls, *deletedLS)
_, err = r.Persister().GetRememberedLoginSession(s.t1, nil, ls.ID)
require.Error(t, err)
})
}
}
func (s *PersisterTestSuite) TestDeleteOpenIDConnectSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
request := fosite.NewRequest()
request.Client = &fosite.DefaultClient{ID: "client-id"}
authorizeCode := uuid.Must(uuid.NewV4()).String()
require.NoError(t, r.Persister().CreateOpenIDConnectSession(s.t1, authorizeCode, request))
actual := persistencesql.OAuth2RequestSQL{Table: "oidc"}
require.NoError(t, r.Persister().DeleteOpenIDConnectSession(s.t2, authorizeCode))
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, authorizeCode))
require.NoError(t, r.Persister().DeleteOpenIDConnectSession(s.t1, authorizeCode))
require.Error(t, r.Persister().Connection(context.Background()).Find(&actual, authorizeCode))
})
}
}
func (s *PersisterTestSuite) TestDeletePKCERequestSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
request := fosite.NewRequest()
request.Client = &fosite.DefaultClient{ID: "client-id"}
authorizeCode := uuid.Must(uuid.NewV4()).String()
r.Persister().CreatePKCERequestSession(s.t1, authorizeCode, request)
actual := persistencesql.OAuth2RequestSQL{Table: "pkce"}
require.NoError(t, r.Persister().DeletePKCERequestSession(s.t2, authorizeCode))
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, authorizeCode))
require.NoError(t, r.Persister().DeletePKCERequestSession(s.t1, authorizeCode))
require.Error(t, r.Persister().Connection(context.Background()).Find(&actual, authorizeCode))
})
}
}
func (s *PersisterTestSuite) TestDeleteRefreshTokenSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
request := fosite.NewRequest()
request.Client = &fosite.DefaultClient{ID: "client-id"}
signature := uuid.Must(uuid.NewV4()).String()
require.NoError(t, r.Persister().CreateRefreshTokenSession(s.t1, signature, request))
actual := persistencesql.OAuth2RequestSQL{Table: "refresh"}
require.NoError(t, r.Persister().DeleteRefreshTokenSession(s.t2, signature))
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, signature))
require.NoError(t, r.Persister().DeleteRefreshTokenSession(s.t1, signature))
require.Error(t, r.Persister().Connection(context.Background()).Find(&actual, signature))
})
}
}
func (s *PersisterTestSuite) TestDetermineNetwork() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
store, ok := r.OAuth2Storage().(*persistencesql.Persister)
if !ok {
t.Fatal("type assertion failed")
}
r.Persister().Connection(context.Background()).Where("id <> ? AND id <> ?", s.t1NID, s.t2NID).Delete(&networkx.Network{})
actual, err := store.DetermineNetwork(context.Background())
require.NoError(t, err)
require.True(t, actual.ID == s.t1NID || actual.ID == s.t2NID)
})
}
}
func (s *PersisterTestSuite) TestFindGrantedAndRememberedConsentRequests() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
sessionID := uuid.Must(uuid.NewV4()).String()
client := &client.Client{LegacyClientID: "client-id"}
f := newFlow(s.t1NID, client.LegacyClientID, "sub", sqlxx.NullString(sessionID))
persistLoginSession(s.t1, t, r.Persister(), &flow.LoginSession{ID: sessionID})
require.NoError(t, r.Persister().CreateClient(s.t1, client))
req := &flow.OAuth2ConsentRequest{
ID: "consent-request-id",
LoginChallenge: sqlxx.NullString(f.ID),
Skip: false,
Verifier: "verifier",
CSRF: "csrf",
}
hcr := &flow.AcceptOAuth2ConsentRequest{
ID: req.ID,
HandledAt: sqlxx.NullTime(time.Now()),
Remember: true,
}
require.NoError(t, r.Persister().CreateConsentRequest(s.t1, f, req))
_, err := r.Persister().HandleConsentRequest(s.t1, f, hcr)
require.NoError(t, err)
require.NoError(t, r.Persister().Connection(context.Background()).Create(f))
actual, err := r.Persister().FindGrantedAndRememberedConsentRequests(s.t2, client.LegacyClientID, f.Subject)
require.Error(t, err)
require.Equal(t, 0, len(actual))
actual, err = r.Persister().FindGrantedAndRememberedConsentRequests(s.t1, client.LegacyClientID, f.Subject)
require.NoError(t, err)
require.Equal(t, 1, len(actual))
})
}
}
func (s *PersisterTestSuite) TestFindSubjectsGrantedConsentRequests() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
sessionID := uuid.Must(uuid.NewV4()).String()
client := &client.Client{LegacyClientID: "client-id"}
f := newFlow(s.t1NID, client.LegacyClientID, "sub", sqlxx.NullString(sessionID))
persistLoginSession(s.t1, t, r.Persister(), &flow.LoginSession{ID: sessionID})
require.NoError(t, r.Persister().CreateClient(s.t1, client))
require.NoError(t, r.Persister().Connection(context.Background()).Create(f))
req := &flow.OAuth2ConsentRequest{
ID: "consent-request-id",
LoginChallenge: sqlxx.NullString(f.ID),
Skip: false,
Verifier: "verifier",
CSRF: "csrf",
}
hcr := &flow.AcceptOAuth2ConsentRequest{
ID: req.ID,
HandledAt: sqlxx.NullTime(time.Now()),
Remember: true,
}
require.NoError(t, r.Persister().CreateConsentRequest(s.t1, f, req))
_, err := r.Persister().HandleConsentRequest(s.t1, f, hcr)
require.NoError(t, err)
actual, err := r.Persister().FindSubjectsGrantedConsentRequests(s.t2, f.Subject, 100, 0)
require.Error(t, err)
require.Equal(t, 0, len(actual))
actual, err = r.Persister().FindSubjectsGrantedConsentRequests(s.t1, f.Subject, 100, 0)
require.NoError(t, err)
require.Equal(t, 1, len(actual))
})
}
}
func (s *PersisterTestSuite) TestFlushInactiveAccessTokens() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
sig := uuid.Must(uuid.NewV4()).String()
fr := fosite.NewRequest()
fr.RequestedAt = time.Now().UTC().Add(-24 * time.Hour)
fr.Client = &fosite.DefaultClient{ID: client.LegacyClientID}
require.NoError(t, r.Persister().CreateAccessTokenSession(s.t1, sig, fr))
actual := persistencesql.OAuth2RequestSQL{Table: "access"}
require.NoError(t, r.Persister().FlushInactiveAccessTokens(s.t2, time.Now().Add(time.Hour), 100, 100))
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, persistencesql.SignatureHash(sig)))
require.NoError(t, r.Persister().FlushInactiveAccessTokens(s.t1, time.Now().Add(time.Hour), 100, 100))
require.Error(t, r.Persister().Connection(context.Background()).Find(&actual, persistencesql.SignatureHash(sig)))
})
}
}
func (s *PersisterTestSuite) TestGenerateAndPersistKeySet() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
store, ok := r.OAuth2Storage().(*persistencesql.Persister)
if !ok {
t.Fatal("type assertion failed")
}
actual := &jwk.SQLData{}
ks, err := store.GenerateAndPersistKeySet(s.t1, "ks", "kid", "RS256", "use")
require.NoError(t, err)
require.Error(t, r.Persister().Connection(context.Background()).Where("sid = ? AND kid = ? AND nid = ?", "ks", ks.Keys[0].KeyID, s.t2NID).First(actual))
require.NoError(t, r.Persister().Connection(context.Background()).Where("sid = ? AND kid = ? AND nid = ?", "ks", ks.Keys[0].KeyID, s.t1NID).First(actual))
})
}
}
func (s *PersisterTestSuite) TestFlushInactiveGrants() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
ks := newKeySet("ks-id", "use")
grant := trust.Grant{
ID: uuid.Must(uuid.NewV4()).String(),
ExpiresAt: time.Now().Add(-24 * time.Hour),
PublicKey: trust.PublicKey{Set: "ks-id", KeyID: ks.Keys[0].KeyID},
}
require.NoError(t, r.Persister().AddKeySet(s.t1, "ks-id", ks))
require.NoError(t, r.Persister().CreateGrant(s.t1, grant, ks.Keys[0]))
actual := trust.SQLData{}
require.NoError(t, r.Persister().FlushInactiveGrants(s.t2, time.Now(), 100, 100))
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, grant.ID))
require.NoError(t, r.Persister().FlushInactiveGrants(s.t1, time.Now(), 100, 100))
require.Error(t, r.Persister().Connection(context.Background()).Find(&actual, grant.ID))
})
}
}
func (s *PersisterTestSuite) TestFlushInactiveLoginConsentRequests() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
sessionID := uuid.Must(uuid.NewV4()).String()
client := &client.Client{LegacyClientID: "client-id"}
f := newFlow(s.t1NID, client.LegacyClientID, "sub", sqlxx.NullString(sessionID))
f.RequestedAt = time.Now().Add(-24 * time.Hour)
persistLoginSession(s.t1, t, r.Persister(), &flow.LoginSession{ID: sessionID})
require.NoError(t, r.Persister().CreateClient(s.t1, client))
require.NoError(t, r.Persister().Connection(context.Background()).Create(f))
actual := flow.Flow{}
require.NoError(t, r.Persister().FlushInactiveLoginConsentRequests(s.t2, time.Now(), 100, 100))
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, f.ID))
require.NoError(t, r.Persister().FlushInactiveLoginConsentRequests(s.t1, time.Now(), 100, 100))
require.Error(t, r.Persister().Connection(context.Background()).Find(&actual, f.ID))
})
}
}
func (s *PersisterTestSuite) TestFlushInactiveRefreshTokens() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
request := fosite.NewRequest()
request.RequestedAt = time.Now().Add(-240 * 365 * time.Hour)
request.Client = &fosite.DefaultClient{ID: "client-id"}
signature := uuid.Must(uuid.NewV4()).String()
require.NoError(t, r.Persister().CreateClient(s.t1, client))
require.NoError(t, r.Persister().CreateRefreshTokenSession(s.t1, signature, request))
actual := persistencesql.OAuth2RequestSQL{Table: "refresh"}
require.NoError(t, r.Persister().FlushInactiveRefreshTokens(s.t2, time.Now(), 100, 100))
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, signature))
require.NoError(t, r.Persister().FlushInactiveRefreshTokens(s.t1, time.Now(), 100, 100))
require.Error(t, r.Persister().Connection(context.Background()).Find(&actual, signature))
})
}
}
func (s *PersisterTestSuite) TestGetAccessTokenSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
sig := uuid.Must(uuid.NewV4()).String()
fr := fosite.NewRequest()
fr.Client = &fosite.DefaultClient{ID: client.LegacyClientID}
require.NoError(t, r.Persister().CreateAccessTokenSession(s.t1, sig, fr))
actual, err := r.Persister().GetAccessTokenSession(s.t2, sig, &fosite.DefaultSession{})
require.Error(t, err)
require.Nil(t, actual)
actual, err = r.Persister().GetAccessTokenSession(s.t1, sig, &fosite.DefaultSession{})
require.NoError(t, err)
require.NotNil(t, actual)
})
}
}
func (s *PersisterTestSuite) TestGetAuthorizeCodeSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
sig := uuid.Must(uuid.NewV4()).String()
fr := fosite.NewRequest()
fr.Client = &fosite.DefaultClient{ID: client.LegacyClientID}
require.NoError(t, r.Persister().CreateAuthorizeCodeSession(s.t1, sig, fr))
actual, err := r.Persister().GetAuthorizeCodeSession(s.t2, sig, &fosite.DefaultSession{})
require.Error(t, err)
require.Nil(t, actual)
actual, err = r.Persister().GetAuthorizeCodeSession(s.t1, sig, &fosite.DefaultSession{})
require.NoError(t, err)
require.NotNil(t, actual)
})
}
}
func (s *PersisterTestSuite) TestGetClient() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
expected := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, expected))
actual, err := r.Persister().GetClient(s.t2, expected.LegacyClientID)
require.Error(t, err)
require.Nil(t, actual)
actual, err = r.Persister().GetClient(s.t1, expected.LegacyClientID)
require.NoError(t, err)
require.Equal(t, expected.LegacyClientID, actual.GetID())
})
}
}
func (s *PersisterTestSuite) TestGetClientAssertionJWT() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
store, ok := r.OAuth2Storage().(oauth2.AssertionJWTReader)
if !ok {
t.Fatal("type assertion failed")
}
expected := oauth2.NewBlacklistedJTI(uuid.Must(uuid.NewV4()).String(), time.Now().Add(24*time.Hour))
require.NoError(t, r.Persister().SetClientAssertionJWT(s.t1, expected.JTI, expected.Expiry))
_, err := store.GetClientAssertionJWT(s.t2, expected.JTI)
require.Error(t, err)
_, err = store.GetClientAssertionJWT(s.t1, expected.JTI)
require.NoError(t, err)
})
}
}
func (s *PersisterTestSuite) TestGetClients() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
c := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, c))
actual, err := r.Persister().GetClients(s.t2, client.Filter{Offset: 0, Limit: 100})
require.NoError(t, err)
require.Equal(t, 0, len(actual))
actual, err = r.Persister().GetClients(s.t1, client.Filter{Offset: 0, Limit: 100})
require.NoError(t, err)
require.Equal(t, 1, len(actual))
})
}
}
func (s *PersisterTestSuite) TestGetConcreteClient() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
expected := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, expected))
actual, err := r.Persister().GetConcreteClient(s.t2, expected.LegacyClientID)
require.Error(t, err)
require.Nil(t, actual)
actual, err = r.Persister().GetConcreteClient(s.t1, expected.LegacyClientID)
require.NoError(t, err)
require.Equal(t, expected.LegacyClientID, actual.GetID())
})
}
}
func (s *PersisterTestSuite) TestGetConcreteGrant() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
ks := newKeySet("ks-id", "use")
grant := trust.Grant{
ID: uuid.Must(uuid.NewV4()).String(),
ExpiresAt: time.Now().Add(time.Hour),
PublicKey: trust.PublicKey{Set: "ks-id", KeyID: ks.Keys[0].KeyID},
}
require.NoError(t, r.Persister().AddKeySet(s.t1, "ks-id", ks))
require.NoError(t, r.Persister().CreateGrant(s.t1, grant, ks.Keys[0]))
actual, err := r.Persister().GetConcreteGrant(s.t2, grant.ID)
require.Error(t, err)
require.Equal(t, trust.Grant{}, actual)
actual, err = r.Persister().GetConcreteGrant(s.t1, grant.ID)
require.NoError(t, err)
require.NotEqual(t, trust.Grant{}, actual)
})
}
}
func (s *PersisterTestSuite) TestGetConsentRequest() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
sessionID := uuid.Must(uuid.NewV4()).String()
client := &client.Client{LegacyClientID: "client-id"}
f := newFlow(s.t1NID, client.LegacyClientID, "sub", sqlxx.NullString(sessionID))
persistLoginSession(s.t1, t, r.Persister(), &flow.LoginSession{ID: sessionID})
require.NoError(t, r.Persister().CreateClient(s.t1, client))
require.NoError(t, r.Persister().Connection(context.Background()).Create(f))
req := &flow.OAuth2ConsentRequest{
ID: x.Must(f.ToConsentChallenge(s.t1, r)),
LoginChallenge: sqlxx.NullString(f.ID),
Skip: false,
Verifier: "verifier",
CSRF: "csrf",
}
require.NoError(t, r.Persister().CreateConsentRequest(s.t1, f, req))
actual, err := r.Persister().GetConsentRequest(s.t2, req.ID)
require.Error(t, err)
require.Nil(t, actual)
actual, err = r.Persister().GetConsentRequest(s.t1, req.ID)
require.NoError(t, err)
require.NotNil(t, actual)
})
}
}
func (s *PersisterTestSuite) TestGetFlow() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
sessionID := uuid.Must(uuid.NewV4()).String()
client := &client.Client{LegacyClientID: "client-id"}
f := newFlow(s.t1NID, client.LegacyClientID, "sub", sqlxx.NullString(sessionID))
persistLoginSession(s.t1, t, r.Persister(), &flow.LoginSession{ID: sessionID})
require.NoError(t, r.Persister().CreateClient(s.t1, client))
require.NoError(t, r.Persister().Connection(context.Background()).Create(f))
store, ok := r.Persister().(*persistencesql.Persister)
if !ok {
t.Fatal("type assertion failed")
}
_, err := store.GetFlow(s.t2, f.ID)
require.Error(t, err)
_, err = store.GetFlow(s.t1, f.ID)
require.NoError(t, err)
})
}
}
func (s *PersisterTestSuite) TestGetFlowByConsentChallenge() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
sessionID := uuid.Must(uuid.NewV4()).String()
client := &client.Client{LegacyClientID: "client-id"}
f := newFlow(s.t1NID, client.LegacyClientID, "sub", sqlxx.NullString(sessionID))
require.NoError(t, r.Persister().CreateLoginSession(s.t1, &flow.LoginSession{ID: sessionID}))
require.NoError(t, r.Persister().CreateClient(s.t1, client))
store, ok := r.Persister().(*persistencesql.Persister)
if !ok {
t.Fatal("type assertion failed")
}
challenge := x.Must(f.ToConsentChallenge(s.t1, r))
_, err := store.GetFlowByConsentChallenge(s.t2, challenge)
require.Error(t, err)
_, err = store.GetFlowByConsentChallenge(s.t1, challenge)
require.NoError(t, err)
})
}
}
func (s *PersisterTestSuite) TestGetForcedObfuscatedLoginSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
session := &consent.ForcedObfuscatedLoginSession{ClientID: client.LegacyClientID}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
require.NoError(t, r.Persister().CreateForcedObfuscatedLoginSession(s.t1, session))
actual, err := r.Persister().GetForcedObfuscatedLoginSession(s.t2, client.LegacyClientID, "")
require.Error(t, err)
require.Nil(t, actual)
actual, err = r.Persister().GetForcedObfuscatedLoginSession(s.t1, client.LegacyClientID, "")
require.NoError(t, err)
require.NotNil(t, actual)
})
}
}
func (s *PersisterTestSuite) TestGetGrants() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
ks := newKeySet("ks-id", "use")
grant := trust.Grant{
ID: uuid.Must(uuid.NewV4()).String(),
ExpiresAt: time.Now().Add(time.Hour),
PublicKey: trust.PublicKey{Set: "ks-id", KeyID: ks.Keys[0].KeyID},
}
require.NoError(t, r.Persister().AddKeySet(s.t1, "ks-id", ks))
require.NoError(t, r.Persister().CreateGrant(s.t1, grant, ks.Keys[0]))
actual, err := r.Persister().GetGrants(s.t2, 100, 0, "")
require.NoError(t, err)
require.Equal(t, 0, len(actual))
actual, err = r.Persister().GetGrants(s.t1, 100, 0, "")
require.NoError(t, err)
require.Equal(t, 1, len(actual))
})
}
}
func (s *PersisterTestSuite) TestGetLoginRequest() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
lr := flow.LoginRequest{ID: "lr-id", ClientID: client.LegacyClientID, RequestedAt: time.Now()}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
f, err := r.ConsentManager().CreateLoginRequest(s.t1, &lr)
require.NoError(t, err)
require.Equal(t, s.t1NID, f.NID)
challenge := x.Must(f.ToLoginChallenge(s.t1, r))
actual, err := r.Persister().GetLoginRequest(s.t2, challenge)
require.Error(t, err)
require.Nil(t, actual)
actual, err = r.Persister().GetLoginRequest(s.t1, challenge)
require.NoError(t, err)
require.NotNil(t, actual)
})
}
}
func (s *PersisterTestSuite) TestGetLogoutRequest() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
lr := flow.LogoutRequest{
ID: uuid.Must(uuid.NewV4()).String(),
ClientID: sql.NullString{Valid: true, String: client.LegacyClientID},
}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
require.NoError(t, r.Persister().CreateLogoutRequest(s.t1, &lr))
actual, err := r.Persister().GetLogoutRequest(s.t2, lr.ID)
require.Error(t, err)
require.Equal(t, &flow.LogoutRequest{}, actual)
actual, err = r.Persister().GetLogoutRequest(s.t1, lr.ID)
require.NoError(t, err)
require.NotEqual(t, &flow.LogoutRequest{}, actual)
})
}
}
func (s *PersisterTestSuite) TestGetOpenIDConnectSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
request := fosite.NewRequest()
request.SetID("request-id")
request.Client = &fosite.DefaultClient{ID: "client-id"}
authorizeCode := uuid.Must(uuid.NewV4()).String()
require.NoError(t, r.Persister().CreateClient(s.t1, client))
require.NoError(t, r.Persister().CreateOpenIDConnectSession(s.t1, authorizeCode, request))
actual, err := r.Persister().GetOpenIDConnectSession(s.t2, authorizeCode, &fosite.Request{})
require.Error(t, err)
require.Nil(t, actual)
actual, err = r.Persister().GetOpenIDConnectSession(s.t1, authorizeCode, &fosite.Request{})
require.NoError(t, err)
require.Equal(t, request.GetID(), actual.GetID())
})
}
}
func (s *PersisterTestSuite) TestGetPKCERequestSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
request := fosite.NewRequest()
request.SetID("request-id")
request.Client = &fosite.DefaultClient{ID: "client-id"}
sig := uuid.Must(uuid.NewV4()).String()
require.NoError(t, r.Persister().CreateClient(s.t1, client))
require.NoError(t, r.Persister().CreatePKCERequestSession(s.t1, sig, request))
actual, err := r.Persister().GetPKCERequestSession(s.t2, sig, &fosite.DefaultSession{})
require.Error(t, err)
require.Nil(t, actual)
actual, err = r.Persister().GetPKCERequestSession(s.t1, sig, &fosite.DefaultSession{})
require.NoError(t, err)
require.Equal(t, request.GetID(), actual.GetID())
})
}
}
func (s *PersisterTestSuite) TestGetPublicKey() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
ks := newKeySet("ks-id", "use")
grant := trust.Grant{
ID: uuid.Must(uuid.NewV4()).String(),
ExpiresAt: time.Now().Add(time.Hour),
PublicKey: trust.PublicKey{Set: "ks-id", KeyID: ks.Keys[0].KeyID},
}
require.NoError(t, r.Persister().AddKeySet(s.t1, "ks-id", ks))
require.NoError(t, r.Persister().CreateGrant(s.t1, grant, ks.Keys[0]))
actual, err := r.Persister().GetPublicKey(s.t2, grant.Issuer, grant.Subject, grant.PublicKey.KeyID)
require.Error(t, err)
require.Nil(t, actual)
actual, err = r.Persister().GetPublicKey(s.t1, grant.Issuer, grant.Subject, grant.PublicKey.KeyID)
require.NoError(t, err)
require.NotNil(t, actual)
})
}
}
func (s *PersisterTestSuite) TestGetPublicKeyScopes() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
ks := newKeySet("ks-id", "use")
grant := trust.Grant{
ID: uuid.Must(uuid.NewV4()).String(),
Scope: []string{"a", "b", "c"},
ExpiresAt: time.Now().Add(time.Hour),
PublicKey: trust.PublicKey{Set: "ks-id", KeyID: ks.Keys[0].KeyID},
}
require.NoError(t, r.Persister().AddKeySet(s.t1, "ks-id", ks))
require.NoError(t, r.Persister().CreateGrant(s.t1, grant, ks.Keys[0]))
actual, err := r.Persister().GetPublicKeyScopes(s.t2, grant.Issuer, grant.Subject, grant.PublicKey.KeyID)
require.Error(t, err)
require.Nil(t, actual)
actual, err = r.Persister().GetPublicKeyScopes(s.t1, grant.Issuer, grant.Subject, grant.PublicKey.KeyID)
require.NoError(t, err)
require.Equal(t, grant.Scope, actual)
})
}
}
func (s *PersisterTestSuite) TestGetPublicKeys() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
ks := newKeySet("ks-id", "use")
grant := trust.Grant{
ID: uuid.Must(uuid.NewV4()).String(),
ExpiresAt: time.Now().Add(time.Hour),
PublicKey: trust.PublicKey{Set: "ks-id", KeyID: ks.Keys[0].KeyID},
}
require.NoError(t, r.Persister().AddKeySet(s.t1, "ks-id", ks))
require.NoError(t, r.Persister().CreateGrant(s.t1, grant, ks.Keys[0]))
actual, err := r.Persister().GetPublicKeys(s.t2, grant.Issuer, grant.Subject)
require.NoError(t, err)
require.Nil(t, actual.Keys)
actual, err = r.Persister().GetPublicKeys(s.t1, grant.Issuer, grant.Subject)
require.NoError(t, err)
require.NotNil(t, actual.Keys)
})
}
}
func (s *PersisterTestSuite) TestGetRefreshTokenSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
request := fosite.NewRequest()
request.SetID("request-id")
request.Client = &fosite.DefaultClient{ID: "client-id"}
sig := uuid.Must(uuid.NewV4()).String()
require.NoError(t, r.Persister().CreateClient(s.t1, client))
require.NoError(t, r.Persister().CreateRefreshTokenSession(s.t1, sig, request))
actual, err := r.Persister().GetRefreshTokenSession(s.t2, sig, &fosite.DefaultSession{})
require.Error(t, err)
require.Nil(t, actual)
actual, err = r.Persister().GetRefreshTokenSession(s.t1, sig, &fosite.DefaultSession{})
require.NoError(t, err)
require.Equal(t, request.GetID(), actual.GetID())
})
}
}
func (s *PersisterTestSuite) TestGetRememberedLoginSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
ls := flow.LoginSession{ID: uuid.Must(uuid.NewV4()).String(), Remember: true}
require.NoError(t, r.Persister().CreateLoginSession(s.t1, &ls))
actual, err := r.Persister().GetRememberedLoginSession(s.t2, &ls, ls.ID)
require.Error(t, err)
require.Nil(t, actual)
actual, err = r.Persister().GetRememberedLoginSession(s.t1, &ls, ls.ID)
require.NoError(t, err)
require.NotNil(t, actual)
})
}
}
func (s *PersisterTestSuite) TestHandleConsentRequest() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
sessionID := uuid.Must(uuid.NewV4()).String()
c1 := &client.Client{LegacyClientID: uuidx.NewV4().String()}
f := newFlow(s.t1NID, c1.LegacyClientID, "sub", sqlxx.NullString(sessionID))
persistLoginSession(s.t1, t, r.Persister(), &flow.LoginSession{ID: sessionID})
require.NoError(t, r.Persister().CreateClient(s.t1, c1))
c1.ID = uuid.Nil
require.NoError(t, r.Persister().CreateClient(s.t2, c1))
req := &flow.OAuth2ConsentRequest{
ID: "consent-request-id",
LoginChallenge: sqlxx.NullString(f.ID),
Skip: false,
Verifier: "verifier",
CSRF: "csrf",
}
hcr := &flow.AcceptOAuth2ConsentRequest{
ID: req.ID,
HandledAt: sqlxx.NullTime(time.Now()),
Remember: true,
}
require.NoError(t, r.Persister().CreateConsentRequest(s.t1, f, req))
actualCR, err := r.Persister().HandleConsentRequest(s.t2, f, hcr)
require.Error(t, err)
require.Nil(t, actualCR)
actual, err := r.Persister().FindGrantedAndRememberedConsentRequests(s.t1, c1.LegacyClientID, f.Subject)
require.Error(t, err)
require.Equal(t, 0, len(actual))
actualCR, err = r.Persister().HandleConsentRequest(s.t1, f, hcr)
require.NoError(t, err)
require.NotNil(t, actualCR)
require.NoError(t, r.Persister().Connection(context.Background()).Create(f))
actual, err = r.Persister().FindGrantedAndRememberedConsentRequests(s.t1, c1.LegacyClientID, f.Subject)
require.NoError(t, err)
require.Equal(t, 1, len(actual))
})
}
}
func (s *PersisterTestSuite) TestInvalidateAuthorizeCodeSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: uuidx.NewV4().String()}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
client.ID = uuid.Nil
require.NoError(t, r.Persister().CreateClient(s.t2, client))
sig := uuid.Must(uuid.NewV4()).String()
fr := fosite.NewRequest()
fr.Client = &fosite.DefaultClient{ID: client.LegacyClientID}
require.NoError(t, r.Persister().CreateAuthorizeCodeSession(s.t1, sig, fr))
require.NoError(t, r.Persister().InvalidateAuthorizeCodeSession(s.t2, sig))
actual := persistencesql.OAuth2RequestSQL{Table: "code"}
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, sig))
require.Equal(t, true, actual.Active)
require.NoError(t, r.Persister().InvalidateAuthorizeCodeSession(s.t1, sig))
actual = persistencesql.OAuth2RequestSQL{Table: "code"}
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, sig))
require.Equal(t, false, actual.Active)
})
}
}
func (s *PersisterTestSuite) TestIsJWTUsed() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
jti := oauth2.NewBlacklistedJTI(uuid.Must(uuid.NewV4()).String(), time.Now().Add(24*time.Hour))
require.NoError(t, r.Persister().SetClientAssertionJWT(s.t1, jti.JTI, jti.Expiry))
actual, err := r.Persister().IsJWTUsed(s.t2, jti.JTI)
require.NoError(t, err)
require.False(t, actual)
actual, err = r.Persister().IsJWTUsed(s.t1, jti.JTI)
require.NoError(t, err)
require.True(t, actual)
})
}
}
func (s *PersisterTestSuite) TestListUserAuthenticatedClientsWithBackChannelLogout() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
c1 := &client.Client{LegacyClientID: "client-1", BackChannelLogoutURI: "not-null"}
c2 := &client.Client{LegacyClientID: "client-2", BackChannelLogoutURI: "not-null"}
require.NoError(t, r.Persister().CreateClient(s.t1, c1))
c1.ID = uuid.Nil
require.NoError(t, r.Persister().CreateClient(s.t2, c1))
require.NoError(t, r.Persister().CreateClient(s.t2, c2))
t1f1 := newFlow(s.t1NID, c1.LegacyClientID, "sub", sqlxx.NullString(uuid.Must(uuid.NewV4()).String()))
t1f1.ConsentChallengeID = "t1f1-consent-challenge"
t1f1.LoginVerifier = "t1f1-login-verifier"
t1f1.ConsentVerifier = "t1f1-consent-verifier"
t2f1 := newFlow(s.t2NID, c1.LegacyClientID, "sub", t1f1.SessionID)
t2f1.ConsentChallengeID = "t2f1-consent-challenge"
t2f1.LoginVerifier = "t2f1-login-verifier"
t2f1.ConsentVerifier = "t2f1-consent-verifier"
t2f2 := newFlow(s.t2NID, c2.LegacyClientID, "sub", t1f1.SessionID)
t2f2.ConsentChallengeID = "t2f2-consent-challenge"
t2f2.LoginVerifier = "t2f2-login-verifier"
t2f2.ConsentVerifier = "t2f2-consent-verifier"
persistLoginSession(s.t1, t, r.Persister(), &flow.LoginSession{ID: t1f1.SessionID.String()})
require.NoError(t, r.Persister().Connection(context.Background()).Create(t1f1))
require.NoError(t, r.Persister().Connection(context.Background()).Create(t2f1))
require.NoError(t, r.Persister().Connection(context.Background()).Create(t2f2))
require.NoError(t, r.Persister().CreateConsentRequest(s.t1, t1f1, &flow.OAuth2ConsentRequest{
ID: t1f1.ID,
LoginChallenge: sqlxx.NullString(t1f1.ID),
Skip: false,
Verifier: t1f1.ConsentVerifier.String(),
CSRF: "csrf",
}))
require.NoError(t, r.Persister().CreateConsentRequest(s.t2, t2f1, &flow.OAuth2ConsentRequest{
ID: t2f1.ID,
LoginChallenge: sqlxx.NullString(t2f1.ID),
Skip: false,
Verifier: t2f1.ConsentVerifier.String(),
CSRF: "csrf",
}))
require.NoError(t, r.Persister().CreateConsentRequest(s.t2, t2f2, &flow.OAuth2ConsentRequest{
ID: t2f2.ID,
LoginChallenge: sqlxx.NullString(t2f2.ID),
Skip: false,
Verifier: t2f2.ConsentVerifier.String(),
CSRF: "csrf",
}))
_, err := r.Persister().HandleConsentRequest(s.t1, t1f1, &flow.AcceptOAuth2ConsentRequest{
ID: t1f1.ID,
HandledAt: sqlxx.NullTime(time.Now()),
Remember: true,
})
require.NoError(t, err)
_, err = r.Persister().HandleConsentRequest(s.t2, t2f1, &flow.AcceptOAuth2ConsentRequest{
ID: t2f1.ID,
HandledAt: sqlxx.NullTime(time.Now()),
Remember: true,
})
require.NoError(t, err)
_, err = r.Persister().HandleConsentRequest(s.t2, t2f2, &flow.AcceptOAuth2ConsentRequest{
ID: t2f2.ID,
HandledAt: sqlxx.NullTime(time.Now()),
Remember: true,
})
require.NoError(t, err)
cs, err := r.Persister().ListUserAuthenticatedClientsWithBackChannelLogout(s.t1, "sub", t1f1.SessionID.String())
require.NoError(t, err)
require.Equal(t, 1, len(cs))
cs, err = r.Persister().ListUserAuthenticatedClientsWithBackChannelLogout(s.t2, "sub", t1f1.SessionID.String())
require.NoError(t, err)
require.Equal(t, 2, len(cs))
})
}
}
func (s *PersisterTestSuite) TestListUserAuthenticatedClientsWithFrontChannelLogout() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
c1 := &client.Client{LegacyClientID: "client-1", FrontChannelLogoutURI: "not-null"}
c2 := &client.Client{LegacyClientID: "client-2", FrontChannelLogoutURI: "not-null"}
require.NoError(t, r.Persister().CreateClient(s.t1, c1))
c1.ID = uuid.Nil
require.NoError(t, r.Persister().CreateClient(s.t2, c1))
require.NoError(t, r.Persister().CreateClient(s.t2, c2))
t1f1 := newFlow(s.t1NID, c1.LegacyClientID, "sub", sqlxx.NullString(uuid.Must(uuid.NewV4()).String()))
t1f1.ConsentChallengeID = "t1f1-consent-challenge"
t1f1.LoginVerifier = "t1f1-login-verifier"
t1f1.ConsentVerifier = "t1f1-consent-verifier"
t2f1 := newFlow(s.t2NID, c1.LegacyClientID, "sub", t1f1.SessionID)
t2f1.ConsentChallengeID = "t2f1-consent-challenge"
t2f1.LoginVerifier = "t2f1-login-verifier"
t2f1.ConsentVerifier = "t2f1-consent-verifier"
t2f2 := newFlow(s.t2NID, c2.LegacyClientID, "sub", t1f1.SessionID)
t2f2.ConsentChallengeID = "t2f2-consent-challenge"
t2f2.LoginVerifier = "t2f2-login-verifier"
t2f2.ConsentVerifier = "t2f2-consent-verifier"
persistLoginSession(s.t1, t, r.Persister(), &flow.LoginSession{ID: t1f1.SessionID.String()})
require.NoError(t, r.Persister().Connection(context.Background()).Create(t1f1))
require.NoError(t, r.Persister().Connection(context.Background()).Create(t2f1))
require.NoError(t, r.Persister().Connection(context.Background()).Create(t2f2))
require.NoError(t, r.Persister().CreateConsentRequest(s.t1, t1f1, &flow.OAuth2ConsentRequest{
ID: t1f1.ID,
LoginChallenge: sqlxx.NullString(t1f1.ID),
Skip: false,
Verifier: t1f1.ConsentVerifier.String(),
CSRF: "csrf",
}))
require.NoError(t, r.Persister().CreateConsentRequest(s.t2, t2f1, &flow.OAuth2ConsentRequest{
ID: t2f1.ID,
LoginChallenge: sqlxx.NullString(t2f1.ID),
Skip: false,
Verifier: t2f1.ConsentVerifier.String(),
CSRF: "csrf",
}))
require.NoError(t, r.Persister().CreateConsentRequest(s.t2, t2f2, &flow.OAuth2ConsentRequest{
ID: t2f2.ID,
LoginChallenge: sqlxx.NullString(t2f2.ID),
Skip: false,
Verifier: t2f2.ConsentVerifier.String(),
CSRF: "csrf",
}))
_, err := r.Persister().HandleConsentRequest(s.t1, t1f1, &flow.AcceptOAuth2ConsentRequest{
ID: t1f1.ID,
HandledAt: sqlxx.NullTime(time.Now()),
Remember: true,
})
require.NoError(t, err)
_, err = r.Persister().HandleConsentRequest(s.t2, t2f1, &flow.AcceptOAuth2ConsentRequest{
ID: t2f1.ID,
HandledAt: sqlxx.NullTime(time.Now()),
Remember: true,
})
require.NoError(t, err)
_, err = r.Persister().HandleConsentRequest(s.t2, t2f2, &flow.AcceptOAuth2ConsentRequest{
ID: t2f2.ID,
HandledAt: sqlxx.NullTime(time.Now()),
Remember: true,
})
require.NoError(t, err)
cs, err := r.Persister().ListUserAuthenticatedClientsWithFrontChannelLogout(s.t1, "sub", t1f1.SessionID.String())
require.NoError(t, err)
require.Equal(t, 1, len(cs))
cs, err = r.Persister().ListUserAuthenticatedClientsWithFrontChannelLogout(s.t2, "sub", t1f1.SessionID.String())
require.NoError(t, err)
require.Equal(t, 2, len(cs))
})
}
}
func (s *PersisterTestSuite) TestMarkJWTUsedForTime() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
r.Persister().SetClientAssertionJWT(s.t1, "a", time.Now().Add(-24*time.Hour))
r.Persister().SetClientAssertionJWT(s.t2, "a", time.Now().Add(-24*time.Hour))
r.Persister().SetClientAssertionJWT(s.t2, "b", time.Now().Add(-24*time.Hour))
require.NoError(t, r.Persister().MarkJWTUsedForTime(s.t2, "a", time.Now().Add(48*time.Hour)))
store, ok := r.OAuth2Storage().(oauth2.AssertionJWTReader)
if !ok {
t.Fatal("type assertion failed")
}
_, err := store.GetClientAssertionJWT(s.t1, "a")
require.NoError(t, err)
_, err = store.GetClientAssertionJWT(s.t2, "a")
require.NoError(t, err)
_, err = store.GetClientAssertionJWT(s.t2, "b")
require.Error(t, err)
})
}
}
func (s *PersisterTestSuite) TestQueryWithNetwork() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
r.Persister().CreateClient(s.t1, &client.Client{LegacyClientID: "client-1", FrontChannelLogoutURI: "not-null"})
store, ok := r.Persister().(*persistencesql.Persister)
if !ok {
t.Fatal("type assertion failed")
}
var actual []client.Client
store.QueryWithNetwork(s.t2).All(&actual)
require.Equal(t, 0, len(actual))
store.QueryWithNetwork(s.t1).All(&actual)
require.Equal(t, 1, len(actual))
})
}
}
func (s *PersisterTestSuite) TestRejectLogoutRequest() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
lr := newLogoutRequest()
require.NoError(t, r.ConsentManager().CreateLogoutRequest(s.t1, lr))
require.Error(t, r.ConsentManager().RejectLogoutRequest(s.t2, lr.ID))
actual, err := r.ConsentManager().GetLogoutRequest(s.t1, lr.ID)
require.NoError(t, err)
require.Equal(t, lr, actual)
require.NoError(t, r.ConsentManager().RejectLogoutRequest(s.t1, lr.ID))
actual, err = r.ConsentManager().GetLogoutRequest(s.t1, lr.ID)
require.Error(t, err)
require.Equal(t, &flow.LogoutRequest{}, actual)
})
}
}
func (s *PersisterTestSuite) TestRevokeAccessToken() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
sig := uuid.Must(uuid.NewV4()).String()
fr := fosite.NewRequest()
fr.Client = &fosite.DefaultClient{ID: client.LegacyClientID}
require.NoError(t, r.Persister().CreateAccessTokenSession(s.t1, sig, fr))
require.NoError(t, r.Persister().RevokeAccessToken(s.t2, fr.ID))
actual := persistencesql.OAuth2RequestSQL{Table: "access"}
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, persistencesql.SignatureHash(sig)))
require.Equal(t, s.t1NID, actual.NID)
require.NoError(t, r.Persister().RevokeAccessToken(s.t1, fr.ID))
require.Error(t, r.Persister().Connection(context.Background()).Find(&actual, persistencesql.SignatureHash(sig)))
})
}
}
func (s *PersisterTestSuite) TestRevokeRefreshToken() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
request := fosite.NewRequest()
request.Client = &fosite.DefaultClient{ID: "client-id"}
signature := uuid.Must(uuid.NewV4()).String()
require.NoError(t, r.Persister().CreateRefreshTokenSession(s.t1, signature, request))
actual := persistencesql.OAuth2RequestSQL{Table: "refresh"}
require.NoError(t, r.Persister().RevokeRefreshToken(s.t2, request.ID))
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, signature))
require.Equal(t, true, actual.Active)
require.NoError(t, r.Persister().RevokeRefreshToken(s.t1, request.ID))
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, signature))
require.Equal(t, false, actual.Active)
})
}
}
func (s *PersisterTestSuite) TestRevokeRefreshTokenMaybeGracePeriod() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
client := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
request := fosite.NewRequest()
request.Client = &fosite.DefaultClient{ID: "client-id"}
signature := uuid.Must(uuid.NewV4()).String()
require.NoError(t, r.Persister().CreateRefreshTokenSession(s.t1, signature, request))
actual := persistencesql.OAuth2RequestSQL{Table: "refresh"}
store, ok := r.Persister().(*persistencesql.Persister)
if !ok {
t.Fatal("type assertion failed")
}
require.NoError(t, store.RevokeRefreshTokenMaybeGracePeriod(s.t2, request.ID, signature))
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, signature))
require.Equal(t, true, actual.Active)
require.NoError(t, store.RevokeRefreshTokenMaybeGracePeriod(s.t1, request.ID, signature))
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, signature))
require.Equal(t, false, actual.Active)
})
}
}
func (s *PersisterTestSuite) TestRevokeSubjectClientConsentSession() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
sessionID := uuid.Must(uuid.NewV4()).String()
client := &client.Client{LegacyClientID: "client-id"}
f := newFlow(s.t1NID, client.LegacyClientID, "sub", sqlxx.NullString(sessionID))
f.RequestedAt = time.Now().Add(-24 * time.Hour)
persistLoginSession(s.t1, t, r.Persister(), &flow.LoginSession{ID: sessionID})
require.NoError(t, r.Persister().CreateClient(s.t1, client))
require.NoError(t, r.Persister().Connection(context.Background()).Create(f))
actual := flow.Flow{}
require.Error(t, r.Persister().RevokeSubjectClientConsentSession(s.t2, "sub", client.LegacyClientID))
require.NoError(t, r.Persister().Connection(context.Background()).Find(&actual, f.ID))
require.NoError(t, r.Persister().RevokeSubjectClientConsentSession(s.t1, "sub", client.LegacyClientID))
require.Error(t, r.Persister().Connection(context.Background()).Find(&actual, f.ID))
})
}
}
func (s *PersisterTestSuite) TestSetClientAssertionJWT() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
jti := oauth2.NewBlacklistedJTI(uuid.Must(uuid.NewV4()).String(), time.Now().Add(24*time.Hour))
require.NoError(t, r.Persister().SetClientAssertionJWT(s.t1, jti.JTI, jti.Expiry))
actual := &oauth2.BlacklistedJTI{}
require.NoError(t, r.Persister().Connection(context.Background()).Find(actual, jti.ID))
require.Equal(t, s.t1NID, actual.NID)
})
}
}
func (s *PersisterTestSuite) TestSetClientAssertionJWTRaw() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
store, ok := r.Persister().(*persistencesql.Persister)
if !ok {
t.Fatal("type assertion failed")
}
jti := oauth2.NewBlacklistedJTI(uuid.Must(uuid.NewV4()).String(), time.Now().Add(24*time.Hour))
require.NoError(t, store.SetClientAssertionJWTRaw(s.t1, jti))
actual := &oauth2.BlacklistedJTI{}
require.NoError(t, r.Persister().Connection(context.Background()).Find(actual, jti.ID))
require.Equal(t, s.t1NID, actual.NID)
})
}
}
func (s *PersisterTestSuite) TestUpdateClient() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
t1c1 := &client.Client{LegacyClientID: "client-id", Name: "original", Secret: "original-secret"}
t2c1 := &client.Client{LegacyClientID: "client-id", Name: "original", Secret: "original-secret"}
require.NoError(t, r.Persister().CreateClient(s.t1, t1c1))
require.NoError(t, r.Persister().CreateClient(s.t2, t2c1))
expectedHash := t1c1.Secret
u1 := *t1c1
u1.Name = "updated"
u1.Secret = ""
require.NoError(t, r.Persister().UpdateClient(s.t2, &u1))
actual := &client.Client{}
require.NoError(t, r.Persister().Connection(context.Background()).Find(actual, t1c1.ID))
require.Equal(t, "original", actual.Name)
require.Equal(t, expectedHash, actual.Secret)
u2 := *t1c1
u2.Name = "updated"
u2.Secret = ""
require.NoError(t, r.Persister().UpdateClient(s.t1, &u2))
require.NoError(t, r.Persister().Connection(context.Background()).Find(actual, t1c1.ID))
require.Equal(t, "updated", actual.Name)
require.Equal(t, expectedHash, actual.Secret)
u3 := *t1c1
u3.Name = "updated"
u3.Secret = "updated-secret"
require.NoError(t, r.Persister().UpdateClient(s.t1, &u3))
require.NoError(t, r.Persister().Connection(context.Background()).Find(actual, t1c1.ID))
require.Equal(t, "updated", actual.Name)
require.NotEqual(t, expectedHash, actual.Secret)
})
}
}
func (s *PersisterTestSuite) TestUpdateKey() {
t := s.T()
for k, r := range s.registries {
t.Run("dialect="+k, func(*testing.T) {
k1 := newKey("test-ks", "test")
ks := "key-set"
require.NoError(t, r.Persister().AddKey(s.t1, ks, &k1))
actual, err := r.Persister().GetKey(s.t1, ks, k1.KeyID)
require.NoError(t, err)
assertx.EqualAsJSON(t, &jose.JSONWebKeySet{Keys: []jose.JSONWebKey{k1}}, actual)
k2 := newKey("test-ks", "test")
r.Persister().UpdateKey(s.t2, ks, &k2)
actual, err = r.Persister().GetKey(s.t1, ks, k1.KeyID)
require.NoError(t, err)
assertx.EqualAsJSON(t, &jose.JSONWebKeySet{Keys: []jose.JSONWebKey{k1}}, actual)
r.Persister().UpdateKey(s.t1, ks, &k2)
actual, err = r.Persister().GetKey(s.t1, ks, k2.KeyID)
require.NoError(t, err)
require.NotEqual(t, &jose.JSONWebKeySet{Keys: []jose.JSONWebKey{k1}}, actual)
})
}
}
func (s *PersisterTestSuite) TestUpdateKeySet() {
t := s.T()
for k, r := range s.registries {
t.Run("dialect="+k, func(*testing.T) {
ks := "key-set"
ks1 := newKeySet(ks, "test")
require.NoError(t, r.Persister().AddKeySet(s.t1, ks, ks1))
actual, err := r.Persister().GetKeySet(s.t1, ks)
require.NoError(t, err)
requireKeySetEqual(t, ks1, actual)
ks2 := newKeySet(ks, "test")
r.Persister().UpdateKeySet(s.t2, ks, ks2)
actual, err = r.Persister().GetKeySet(s.t1, ks)
require.NoError(t, err)
requireKeySetEqual(t, ks1, actual)
r.Persister().UpdateKeySet(s.t1, ks, ks2)
actual, err = r.Persister().GetKeySet(s.t1, ks)
require.NoError(t, err)
requireKeySetEqual(t, ks2, actual)
})
}
}
func (s *PersisterTestSuite) TestUpdateWithNetwork() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
t1c1 := &client.Client{LegacyClientID: "client-id", Name: "original", Secret: "original-secret"}
t2c1 := &client.Client{LegacyClientID: "client-id", Name: "original", Secret: "original-secret", Owner: "erase-me"}
require.NoError(t, r.Persister().CreateClient(s.t1, t1c1))
require.NoError(t, r.Persister().CreateClient(s.t2, t2c1))
store, ok := r.Persister().(*persistencesql.Persister)
if !ok {
t.Fatal("type assertion failed")
}
count, err := store.UpdateWithNetwork(s.t1, &client.Client{ID: t1c1.ID, LegacyClientID: "client-id", Name: "updated", Secret: "original-secret"})
require.NoError(t, err)
require.Equal(t, int64(1), count)
actualt1, err := store.GetConcreteClient(s.t1, "client-id")
require.NoError(t, err)
require.Equal(t, "updated", actualt1.Name)
require.Equal(t, "", actualt1.Owner)
actualt2, err := store.GetConcreteClient(s.t2, "client-id")
require.NoError(t, err)
require.Equal(t, "original", actualt2.Name)
require.Equal(t, "erase-me", actualt2.Owner)
})
}
}
func (s *PersisterTestSuite) TestVerifyAndInvalidateConsentRequest() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
sub := uuid.Must(uuid.NewV4()).String()
sessionID := uuid.Must(uuid.NewV4()).String()
persistLoginSession(s.t1, t, r.Persister(), &flow.LoginSession{ID: sessionID})
client := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
f := newFlow(s.t1NID, client.LegacyClientID, sub, sqlxx.NullString(sessionID))
f.ConsentSkip = false
f.GrantedScope = sqlxx.StringSliceJSONFormat{}
f.ConsentRemember = false
crf := 86400
f.ConsentRememberFor = &crf
f.ConsentError = &flow.RequestDeniedError{}
f.SessionAccessToken = map[string]interface{}{}
f.SessionIDToken = map[string]interface{}{}
f.ConsentWasHandled = false
f.State = flow.FlowStateConsentUnused
consentVerifier := x.Must(f.ToConsentVerifier(s.t1, r))
_, err := r.ConsentManager().VerifyAndInvalidateConsentRequest(s.t2, f, consentVerifier)
require.Error(t, err)
require.Equal(t, flow.FlowStateConsentUnused, f.State)
require.Equal(t, false, f.ConsentWasHandled)
_, err = r.ConsentManager().VerifyAndInvalidateConsentRequest(s.t1, f, consentVerifier)
require.NoError(t, err)
require.Equal(t, flow.FlowStateConsentUsed, f.State)
require.Equal(t, true, f.ConsentWasHandled)
})
}
}
func (s *PersisterTestSuite) TestVerifyAndInvalidateLoginRequest() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
sub := uuid.Must(uuid.NewV4()).String()
sessionID := uuid.Must(uuid.NewV4()).String()
persistLoginSession(s.t1, t, r.Persister(), &flow.LoginSession{ID: sessionID})
client := &client.Client{LegacyClientID: "client-id"}
require.NoError(t, r.Persister().CreateClient(s.t1, client))
f := newFlow(s.t1NID, client.LegacyClientID, sub, sqlxx.NullString(sessionID))
f.State = flow.FlowStateLoginUnused
loginVerifier := x.Must(f.ToLoginVerifier(s.t1, r))
_, err := r.ConsentManager().VerifyAndInvalidateLoginRequest(s.t2, f, loginVerifier)
require.Error(t, err)
require.Equal(t, flow.FlowStateLoginUnused, f.State)
require.Equal(t, false, f.LoginWasUsed)
_, err = r.ConsentManager().VerifyAndInvalidateLoginRequest(s.t1, f, loginVerifier)
require.NoError(t, err)
require.Equal(t, flow.FlowStateLoginUsed, f.State)
require.Equal(t, true, f.LoginWasUsed)
})
}
}
func (s *PersisterTestSuite) TestVerifyAndInvalidateLogoutRequest() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
lr := newLogoutRequest()
lr.Verifier = uuid.Must(uuid.NewV4()).String()
lr.Accepted = true
lr.Rejected = false
require.NoError(t, r.ConsentManager().CreateLogoutRequest(s.t1, lr))
expected, err := r.ConsentManager().GetLogoutRequest(s.t1, lr.ID)
require.NoError(t, err)
lrInvalidated, err := r.ConsentManager().VerifyAndInvalidateLogoutRequest(s.t2, lr.Verifier)
require.Error(t, err)
require.Nil(t, lrInvalidated)
actual := &flow.LogoutRequest{}
require.NoError(t, r.Persister().Connection(context.Background()).Find(actual, lr.ID))
require.Equal(t, expected, actual)
lrInvalidated, err = r.ConsentManager().VerifyAndInvalidateLogoutRequest(s.t1, lr.Verifier)
require.NoError(t, err)
require.NoError(t, r.Persister().Connection(context.Background()).Find(actual, lr.ID))
require.Equal(t, lrInvalidated, actual)
require.Equal(t, true, actual.WasHandled)
})
}
}
func (s *PersisterTestSuite) TestWithFallbackNetworkID() {
t := s.T()
for k, r := range s.registries {
t.Run(k, func(t *testing.T) {
r.WithContextualizer(&contextx.Default{})
store, ok := r.Persister().(*persistencesql.Persister)
if !ok {
t.Fatal("type assertion failed")
}
original := store.NetworkID(context.Background())
expected := uuid.Must(uuid.NewV4())
store, ok = store.WithFallbackNetworkID(expected).(*persistencesql.Persister)
if !ok {
t.Fatal("type assertion failed")
}
require.NotEqual(t, original, expected)
require.Equal(t, expected, store.NetworkID(context.Background()))
})
}
}
func TestPersisterTestSuite(t *testing.T) {
suite.Run(t, new(PersisterTestSuite))
}
func newClient() *client.Client {
return &client.Client{
ID: uuid.Must(uuid.NewV4()),
}
}
func newFlow(nid uuid.UUID, clientID string, subject string, sessionID sqlxx.NullString) *flow.Flow {
return &flow.Flow{
NID: nid,
ID: uuid.Must(uuid.NewV4()).String(),
ClientID: clientID,
Subject: subject,
ConsentError: &flow.RequestDeniedError{},
State: flow.FlowStateConsentUnused,
LoginError: &flow.RequestDeniedError{},
Context: sqlxx.JSONRawMessage{},
AMR: sqlxx.StringSliceJSONFormat{},
ConsentChallengeID: sqlxx.NullString("not-null"),
ConsentVerifier: sqlxx.NullString("not-null"),
ConsentCSRF: sqlxx.NullString("not-null"),
SessionID: sessionID,
RequestedAt: time.Now(),
}
}
func newGrant(keySet string, keyID string) trust.Grant {
return trust.Grant{
ID: uuid.Must(uuid.NewV4()).String(),
ExpiresAt: time.Now().Add(time.Hour),
PublicKey: trust.PublicKey{
Set: keySet,
KeyID: keyID,
},
}
}
func newLogoutRequest() *flow.LogoutRequest {
return &flow.LogoutRequest{
ID: uuid.Must(uuid.NewV4()).String(),
}
}
func newKey(ksID string, use string) jose.JSONWebKey {
ks, err := jwk.GenerateJWK(context.Background(), jose.RS256, ksID, use)
if err != nil {
panic(err)
}
return ks.Keys[0]
}
func newKeySet(id string, use string) *jose.JSONWebKeySet {
return x.Must(jwk.GenerateJWK(context.Background(), jose.RS256, id, use))
}
func newLoginSession() *flow.LoginSession {
return &flow.LoginSession{
ID: uuid.Must(uuid.NewV4()).String(),
AuthenticatedAt: sqlxx.NullTime(time.Time{}),
Subject: uuid.Must(uuid.NewV4()).String(),
Remember: false,
}
}
func requireKeySetEqual(t *testing.T, expected *jose.JSONWebKeySet, actual *jose.JSONWebKeySet) {
assertx.EqualAsJSON(t, expected, actual)
}
func persistLoginSession(ctx context.Context, t *testing.T, p persistence.Persister, session *flow.LoginSession) {
t.Helper()
require.NoError(t, p.CreateLoginSession(ctx, session))
require.NoError(t, p.Connection(ctx).Create(session))
} |
Go | hydra/persistence/sql/persister_nonce.go | // Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package sql
import (
"context"
"time"
"github.com/ory/fosite"
"github.com/ory/hydra/v2/x"
"github.com/ory/x/errorsx"
"github.com/ory/x/otelx"
)
// Set the aadAccessTokenPrefix to something unique to avoid ciphertext confusion with other usages of the AEAD cipher.
var aadAccessTokenPrefix = "vc-nonce-at:" // nolint:gosec
func (p *Persister) NewNonce(ctx context.Context, accessToken string, expiresIn time.Time) (res string, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.NewNonce")
defer otelx.End(span, &err)
plaintext := x.IntToBytes(expiresIn.Unix())
aad := []byte(aadAccessTokenPrefix + accessToken)
return p.r.FlowCipher().Encrypt(ctx, plaintext, aad)
}
func (p *Persister) IsNonceValid(ctx context.Context, accessToken, nonce string) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.IsNonceValid")
defer otelx.End(span, &err)
aad := []byte(aadAccessTokenPrefix + accessToken)
plaintext, err := p.r.FlowCipher().Decrypt(ctx, nonce, aad)
if err != nil {
return errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf("The nonce is invalid."))
}
exp, err := x.BytesToInt(plaintext)
if err != nil {
return errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf("The nonce is invalid.")) // should never happen
}
if exp < time.Now().Unix() {
return errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf("The nonce has expired."))
}
return nil
} |
Go | hydra/persistence/sql/persister_nonce_test.go | // Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package sql_test
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/ory/fosite"
"github.com/ory/hydra/v2/internal"
"github.com/ory/x/contextx"
"github.com/ory/x/randx"
)
func TestPersister_Nonce(t *testing.T) {
ctx := context.Background()
p := internal.NewMockedRegistry(t, new(contextx.Default)).Persister()
accessToken := randx.MustString(100, randx.AlphaNum)
anotherToken := randx.MustString(100, randx.AlphaNum)
validNonce, err := p.NewNonce(ctx, accessToken, time.Now().Add(1*time.Hour))
require.NoError(t, err)
expiredNonce, err := p.NewNonce(ctx, accessToken, time.Now().Add(-1*time.Hour))
require.NoError(t, err)
nonceForAnotherAccessToken, err := p.NewNonce(ctx, anotherToken, time.Now().Add(-1*time.Hour))
require.NoError(t, err)
for _, tc := range []struct {
name string
nonce string
assertErr assert.ErrorAssertionFunc
}{{
name: "valid nonce",
nonce: validNonce,
assertErr: assert.NoError,
}, {
name: "expired nonce",
nonce: expiredNonce,
assertErr: assertInvalidRequest,
}, {
name: "nonce for another access token",
nonce: nonceForAnotherAccessToken,
assertErr: assertInvalidRequest,
},
} {
t.Run("case="+tc.name, func(t *testing.T) {
err := p.IsNonceValid(ctx, accessToken, tc.nonce)
tc.assertErr(t, err)
})
}
}
func assertInvalidRequest(t assert.TestingT, err error, i ...interface{}) bool {
return assert.ErrorIs(t, err, fosite.ErrInvalidRequest)
} |
Go | hydra/persistence/sql/persister_oauth2.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package sql
import (
"context"
"crypto/sha256"
"crypto/sha512"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"net/url"
"strings"
"time"
"go.opentelemetry.io/otel/trace"
"github.com/gofrs/uuid"
"github.com/pkg/errors"
"github.com/tidwall/gjson"
"github.com/ory/fosite"
"github.com/ory/fosite/storage"
"github.com/ory/hydra/v2/oauth2"
"github.com/ory/hydra/v2/x/events"
"github.com/ory/x/errorsx"
"github.com/ory/x/otelx"
"github.com/ory/x/sqlcon"
"github.com/ory/x/stringsx"
)
var _ oauth2.AssertionJWTReader = &Persister{}
var _ storage.Transactional = &Persister{}
type (
tableName string
OAuth2RequestSQL struct {
ID string `db:"signature"`
NID uuid.UUID `db:"nid"`
Request string `db:"request_id"`
ConsentChallenge sql.NullString `db:"challenge_id"`
RequestedAt time.Time `db:"requested_at"`
Client string `db:"client_id"`
Scopes string `db:"scope"`
GrantedScope string `db:"granted_scope"`
RequestedAudience string `db:"requested_audience"`
GrantedAudience string `db:"granted_audience"`
Form string `db:"form_data"`
Subject string `db:"subject"`
Active bool `db:"active"`
Session []byte `db:"session_data"`
Table tableName `db:"-"`
}
)
const (
sqlTableOpenID tableName = "oidc"
sqlTableAccess tableName = "access"
sqlTableRefresh tableName = "refresh"
sqlTableCode tableName = "code"
sqlTablePKCE tableName = "pkce"
)
func (r OAuth2RequestSQL) TableName() string {
return "hydra_oauth2_" + string(r.Table)
}
func (p *Persister) sqlSchemaFromRequest(ctx context.Context, signature string, r fosite.Requester, table tableName) (*OAuth2RequestSQL, error) {
subject := ""
if r.GetSession() == nil {
p.l.Debugf("Got an empty session in sqlSchemaFromRequest")
} else {
subject = r.GetSession().GetSubject()
}
session, err := json.Marshal(r.GetSession())
if err != nil {
return nil, errorsx.WithStack(err)
}
if p.config.EncryptSessionData(ctx) {
ciphertext, err := p.r.KeyCipher().Encrypt(ctx, session, nil)
if err != nil {
return nil, errorsx.WithStack(err)
}
session = []byte(ciphertext)
}
var challenge sql.NullString
rr, ok := r.GetSession().(*oauth2.Session)
if !ok && r.GetSession() != nil {
return nil, errors.Errorf("Expected request to be of type *Session, but got: %T", r.GetSession())
} else if ok {
if len(rr.ConsentChallenge) > 0 {
challenge = sql.NullString{Valid: true, String: rr.ConsentChallenge}
}
}
return &OAuth2RequestSQL{
Request: r.GetID(),
ConsentChallenge: challenge,
ID: signature,
RequestedAt: r.GetRequestedAt(),
Client: r.GetClient().GetID(),
Scopes: strings.Join(r.GetRequestedScopes(), "|"),
GrantedScope: strings.Join(r.GetGrantedScopes(), "|"),
GrantedAudience: strings.Join(r.GetGrantedAudience(), "|"),
RequestedAudience: strings.Join(r.GetRequestedAudience(), "|"),
Form: r.GetRequestForm().Encode(),
Session: session,
Subject: subject,
Active: true,
Table: table,
}, nil
}
func (r *OAuth2RequestSQL) toRequest(ctx context.Context, session fosite.Session, p *Persister) (_ *fosite.Request, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.toRequest")
defer otelx.End(span, &err)
sess := r.Session
if !gjson.ValidBytes(sess) {
var err error
sess, err = p.r.KeyCipher().Decrypt(ctx, string(sess), nil)
if err != nil {
return nil, errorsx.WithStack(err)
}
}
if session != nil {
if err := json.Unmarshal(sess, session); err != nil {
return nil, errorsx.WithStack(err)
}
} else {
p.l.Debugf("Got an empty session in toRequest")
}
c, err := p.GetClient(ctx, r.Client)
if err != nil {
return nil, err
}
val, err := url.ParseQuery(r.Form)
if err != nil {
return nil, errorsx.WithStack(err)
}
return &fosite.Request{
ID: r.Request,
RequestedAt: r.RequestedAt,
Client: c,
RequestedScope: stringsx.Splitx(r.Scopes, "|"),
GrantedScope: stringsx.Splitx(r.GrantedScope, "|"),
RequestedAudience: stringsx.Splitx(r.RequestedAudience, "|"),
GrantedAudience: stringsx.Splitx(r.GrantedAudience, "|"),
Form: val,
Session: session,
}, nil
}
func (p *Persister) ClientAssertionJWTValid(ctx context.Context, jti string) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.ClientAssertionJWTValid")
defer otelx.End(span, &err)
j, err := p.GetClientAssertionJWT(ctx, jti)
if errors.Is(err, sqlcon.ErrNoRows) {
// the jti is not known => valid
return nil
} else if err != nil {
return err
}
if j.Expiry.After(time.Now()) {
// the jti is not expired yet => invalid
return errorsx.WithStack(fosite.ErrJTIKnown)
}
// the jti is expired => valid
return nil
}
func (p *Persister) SetClientAssertionJWT(ctx context.Context, jti string, exp time.Time) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.SetClientAssertionJWT")
defer otelx.End(span, &err)
// delete expired; this cleanup spares us the need for a background worker
if err := p.QueryWithNetwork(ctx).Where("expires_at < CURRENT_TIMESTAMP").Delete(&oauth2.BlacklistedJTI{}); err != nil {
return sqlcon.HandleError(err)
}
if err := p.SetClientAssertionJWTRaw(ctx, oauth2.NewBlacklistedJTI(jti, exp)); errors.Is(err, sqlcon.ErrUniqueViolation) {
// found a jti
return errorsx.WithStack(fosite.ErrJTIKnown)
} else if err != nil {
return err
}
// setting worked without a problem
return nil
}
func (p *Persister) GetClientAssertionJWT(ctx context.Context, j string) (_ *oauth2.BlacklistedJTI, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetClientAssertionJWT")
defer otelx.End(span, &err)
jti := oauth2.NewBlacklistedJTI(j, time.Time{})
return jti, sqlcon.HandleError(p.QueryWithNetwork(ctx).Find(jti, jti.ID))
}
func (p *Persister) SetClientAssertionJWTRaw(ctx context.Context, jti *oauth2.BlacklistedJTI) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.SetClientAssertionJWTRaw")
defer otelx.End(span, &err)
return sqlcon.HandleError(p.CreateWithNetwork(ctx, jti))
}
func (p *Persister) createSession(ctx context.Context, signature string, requester fosite.Requester, table tableName) error {
req, err := p.sqlSchemaFromRequest(ctx, signature, requester, table)
if err != nil {
return err
}
if err = sqlcon.HandleError(p.CreateWithNetwork(ctx, req)); errors.Is(err, sqlcon.ErrConcurrentUpdate) {
return errors.Wrap(fosite.ErrSerializationFailure, err.Error())
} else if err != nil {
return err
}
return nil
}
func (p *Persister) findSessionBySignature(ctx context.Context, signature string, session fosite.Session, table tableName) (fosite.Requester, error) {
r := OAuth2RequestSQL{Table: table}
err := p.QueryWithNetwork(ctx).Where("signature = ?", signature).First(&r)
if errors.Is(err, sql.ErrNoRows) {
return nil, errorsx.WithStack(fosite.ErrNotFound)
}
if err != nil {
return nil, sqlcon.HandleError(err)
}
if !r.Active {
fr, err := r.toRequest(ctx, session, p)
if err != nil {
return nil, err
}
if table == sqlTableCode {
return fr, errorsx.WithStack(fosite.ErrInvalidatedAuthorizeCode)
}
return fr, errorsx.WithStack(fosite.ErrInactiveToken)
}
return r.toRequest(ctx, session, p)
}
func (p *Persister) deleteSessionBySignature(ctx context.Context, signature string, table tableName) error {
err := sqlcon.HandleError(
p.QueryWithNetwork(ctx).
Where("signature = ?", signature).
Delete(&OAuth2RequestSQL{Table: table}))
if errors.Is(err, sqlcon.ErrNoRows) {
return errorsx.WithStack(fosite.ErrNotFound)
}
if errors.Is(err, sqlcon.ErrConcurrentUpdate) {
return errors.Wrap(fosite.ErrSerializationFailure, err.Error())
}
return err
}
func (p *Persister) deleteSessionByRequestID(ctx context.Context, id string, table tableName) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.deleteSessionByRequestID")
defer otelx.End(span, &err)
err = p.QueryWithNetwork(ctx).
Where("request_id=?", id).
Delete(&OAuth2RequestSQL{Table: table})
if errors.Is(err, sql.ErrNoRows) {
return errorsx.WithStack(fosite.ErrNotFound)
}
if err := sqlcon.HandleError(err); err != nil {
if errors.Is(err, sqlcon.ErrConcurrentUpdate) {
return errors.Wrap(fosite.ErrSerializationFailure, err.Error())
}
if strings.Contains(err.Error(), "Error 1213") { // InnoDB Deadlock?
return errors.Wrap(fosite.ErrSerializationFailure, err.Error())
}
return err
}
return nil
}
func (p *Persister) deactivateSessionByRequestID(ctx context.Context, id string, table tableName) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.deactivateSessionByRequestID")
defer otelx.End(span, &err)
/* #nosec G201 table is static */
return sqlcon.HandleError(
p.Connection(ctx).
RawQuery(
fmt.Sprintf("UPDATE %s SET active=false WHERE request_id=? AND nid = ? AND active=true", OAuth2RequestSQL{Table: table}.TableName()),
id,
p.NetworkID(ctx),
).
Exec(),
)
}
func (p *Persister) CreateAuthorizeCodeSession(ctx context.Context, signature string, requester fosite.Requester) error {
return otelx.WithSpan(ctx, "persistence.sql.CreateAuthorizeCodeSession", func(ctx context.Context) error {
return p.createSession(ctx, signature, requester, sqlTableCode)
})
}
func (p *Persister) GetAuthorizeCodeSession(ctx context.Context, signature string, session fosite.Session) (request fosite.Requester, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetAuthorizeCodeSession")
defer otelx.End(span, &err)
return p.findSessionBySignature(ctx, signature, session, sqlTableCode)
}
func (p *Persister) InvalidateAuthorizeCodeSession(ctx context.Context, signature string) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.InvalidateAuthorizeCodeSession")
defer otelx.End(span, &err)
/* #nosec G201 table is static */
return sqlcon.HandleError(
p.Connection(ctx).
RawQuery(
fmt.Sprintf("UPDATE %s SET active = false WHERE signature = ? AND nid = ?", OAuth2RequestSQL{Table: sqlTableCode}.TableName()),
signature,
p.NetworkID(ctx),
).
Exec(),
)
}
// SignatureHash hashes the signature to prevent errors where the signature is
// longer than 128 characters (and thus doesn't fit into the pk).
func SignatureHash(signature string) string {
return fmt.Sprintf("%x", sha512.Sum384([]byte(signature)))
}
func (p *Persister) CreateAccessTokenSession(ctx context.Context, signature string, requester fosite.Requester) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.CreateAccessTokenSession")
defer otelx.End(span, &err)
events.Trace(ctx, events.AccessTokenIssued,
append(toEventOptions(requester), events.WithGrantType(requester.GetRequestForm().Get("grant_type")))...,
)
return p.createSession(ctx, SignatureHash(signature), requester, sqlTableAccess)
}
func (p *Persister) GetAccessTokenSession(ctx context.Context, signature string, session fosite.Session) (request fosite.Requester, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetAccessTokenSession")
defer otelx.End(span, &err)
r := OAuth2RequestSQL{Table: sqlTableAccess}
err = p.QueryWithNetwork(ctx).Where("signature = ?", SignatureHash(signature)).First(&r)
if errors.Is(err, sql.ErrNoRows) {
// Backwards compatibility: we previously did not always hash the
// signature before inserting. In case there are still very old (but
// valid) access tokens in the database, this should get them.
err = p.QueryWithNetwork(ctx).Where("signature = ?", signature).First(&r)
if errors.Is(err, sql.ErrNoRows) {
return nil, errorsx.WithStack(fosite.ErrNotFound)
}
}
if err != nil {
return nil, sqlcon.HandleError(err)
}
if !r.Active {
fr, err := r.toRequest(ctx, session, p)
if err != nil {
return nil, err
}
return fr, errorsx.WithStack(fosite.ErrInactiveToken)
}
return r.toRequest(ctx, session, p)
}
func (p *Persister) DeleteAccessTokenSession(ctx context.Context, signature string) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.DeleteAccessTokenSession")
defer otelx.End(span, &err)
err = sqlcon.HandleError(
p.QueryWithNetwork(ctx).
Where("signature = ?", SignatureHash(signature)).
Delete(&OAuth2RequestSQL{Table: sqlTableAccess}))
if errors.Is(err, sqlcon.ErrNoRows) {
// Backwards compatibility: we previously did not always hash the
// signature before inserting. In case there are still very old (but
// valid) access tokens in the database, this should get them.
err = sqlcon.HandleError(
p.QueryWithNetwork(ctx).
Where("signature = ?", signature).
Delete(&OAuth2RequestSQL{Table: sqlTableAccess}))
if errors.Is(err, sqlcon.ErrNoRows) {
return errorsx.WithStack(fosite.ErrNotFound)
}
}
if errors.Is(err, sqlcon.ErrConcurrentUpdate) {
return errors.Wrap(fosite.ErrSerializationFailure, err.Error())
}
return err
}
func toEventOptions(requester fosite.Requester) []trace.EventOption {
sub := ""
if requester.GetSession() != nil {
hash := sha256.Sum256([]byte(requester.GetSession().GetSubject()))
sub = hex.EncodeToString(hash[:])
}
return []trace.EventOption{
events.WithGrantType(requester.GetRequestForm().Get("grant_type")),
events.WithSubject(sub),
events.WithRequest(requester),
events.WithClientID(requester.GetClient().GetID()),
}
}
func (p *Persister) CreateRefreshTokenSession(ctx context.Context, signature string, requester fosite.Requester) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.CreateRefreshTokenSession")
defer otelx.End(span, &err)
events.Trace(ctx, events.RefreshTokenIssued, toEventOptions(requester)...)
return p.createSession(ctx, signature, requester, sqlTableRefresh)
}
func (p *Persister) GetRefreshTokenSession(ctx context.Context, signature string, session fosite.Session) (request fosite.Requester, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetRefreshTokenSession")
defer otelx.End(span, &err)
return p.findSessionBySignature(ctx, signature, session, sqlTableRefresh)
}
func (p *Persister) DeleteRefreshTokenSession(ctx context.Context, signature string) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.DeleteRefreshTokenSession")
defer otelx.End(span, &err)
return p.deleteSessionBySignature(ctx, signature, sqlTableRefresh)
}
func (p *Persister) CreateOpenIDConnectSession(ctx context.Context, signature string, requester fosite.Requester) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.CreateOpenIDConnectSession")
defer otelx.End(span, &err)
events.Trace(ctx, events.IdentityTokenIssued, toEventOptions(requester)...)
return p.createSession(ctx, signature, requester, sqlTableOpenID)
}
func (p *Persister) GetOpenIDConnectSession(ctx context.Context, signature string, requester fosite.Requester) (_ fosite.Requester, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetOpenIDConnectSession")
defer otelx.End(span, &err)
return p.findSessionBySignature(ctx, signature, requester.GetSession(), sqlTableOpenID)
}
func (p *Persister) DeleteOpenIDConnectSession(ctx context.Context, signature string) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.DeleteOpenIDConnectSession")
defer otelx.End(span, &err)
return p.deleteSessionBySignature(ctx, signature, sqlTableOpenID)
}
func (p *Persister) GetPKCERequestSession(ctx context.Context, signature string, session fosite.Session) (_ fosite.Requester, err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.GetPKCERequestSession")
defer otelx.End(span, &err)
return p.findSessionBySignature(ctx, signature, session, sqlTablePKCE)
}
func (p *Persister) CreatePKCERequestSession(ctx context.Context, signature string, requester fosite.Requester) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.CreatePKCERequestSession")
defer otelx.End(span, &err)
return p.createSession(ctx, signature, requester, sqlTablePKCE)
}
func (p *Persister) DeletePKCERequestSession(ctx context.Context, signature string) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.DeletePKCERequestSession")
defer otelx.End(span, &err)
return p.deleteSessionBySignature(ctx, signature, sqlTablePKCE)
}
func (p *Persister) RevokeRefreshToken(ctx context.Context, id string) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.RevokeRefreshToken")
defer otelx.End(span, &err)
return p.deactivateSessionByRequestID(ctx, id, sqlTableRefresh)
}
func (p *Persister) RevokeRefreshTokenMaybeGracePeriod(ctx context.Context, id string, _ string) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.RevokeRefreshTokenMaybeGracePeriod")
defer otelx.End(span, &err)
return p.deactivateSessionByRequestID(ctx, id, sqlTableRefresh)
}
func (p *Persister) RevokeAccessToken(ctx context.Context, id string) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.RevokeAccessToken")
defer otelx.End(span, &err)
return p.deleteSessionByRequestID(ctx, id, sqlTableAccess)
}
func (p *Persister) flushInactiveTokens(ctx context.Context, notAfter time.Time, limit int, batchSize int, table tableName, lifespan time.Duration) (err error) {
/* #nosec G201 table is static */
// The value of notAfter should be the minimum between input parameter and token max expire based on its configured age
requestMaxExpire := time.Now().Add(-lifespan)
if requestMaxExpire.Before(notAfter) {
notAfter = requestMaxExpire
}
totalDeletedCount := 0
for deletedRecords := batchSize; totalDeletedCount < limit && deletedRecords == batchSize; {
d := batchSize
if limit-totalDeletedCount < batchSize {
d = limit - totalDeletedCount
}
// Delete in batches
// The outer SELECT is necessary because our version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery
deletedRecords, err = p.Connection(ctx).RawQuery(
fmt.Sprintf(`DELETE FROM %s WHERE signature in (
SELECT signature FROM (SELECT signature FROM %s hoa WHERE requested_at < ? and nid = ? ORDER BY requested_at LIMIT %d ) as s
)`, OAuth2RequestSQL{Table: table}.TableName(), OAuth2RequestSQL{Table: table}.TableName(), d),
notAfter,
p.NetworkID(ctx),
).ExecWithCount()
totalDeletedCount += deletedRecords
if err != nil {
break
}
p.l.Debugf("Flushing tokens...: %d/%d", totalDeletedCount, limit)
}
p.l.Debugf("Flush Refresh Tokens flushed_records: %d", totalDeletedCount)
return sqlcon.HandleError(err)
}
func (p *Persister) FlushInactiveAccessTokens(ctx context.Context, notAfter time.Time, limit int, batchSize int) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.FlushInactiveAccessTokens")
defer otelx.End(span, &err)
return p.flushInactiveTokens(ctx, notAfter, limit, batchSize, sqlTableAccess, p.config.GetAccessTokenLifespan(ctx))
}
func (p *Persister) FlushInactiveRefreshTokens(ctx context.Context, notAfter time.Time, limit int, batchSize int) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.FlushInactiveRefreshTokens")
defer otelx.End(span, &err)
return p.flushInactiveTokens(ctx, notAfter, limit, batchSize, sqlTableRefresh, p.config.GetRefreshTokenLifespan(ctx))
}
func (p *Persister) DeleteAccessTokens(ctx context.Context, clientID string) (err error) {
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.DeleteAccessTokens")
defer otelx.End(span, &err)
/* #nosec G201 table is static */
return sqlcon.HandleError(
p.QueryWithNetwork(ctx).Where("client_id=?", clientID).Delete(&OAuth2RequestSQL{Table: sqlTableAccess}),
)
} |
Go | hydra/persistence/sql/persister_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package sql_test
import (
"context"
"testing"
"time"
"github.com/go-jose/go-jose/v3"
"github.com/gobuffalo/pop/v6"
"github.com/gofrs/uuid"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/consent"
"github.com/ory/hydra/v2/internal/testhelpers"
"github.com/ory/hydra/v2/oauth2/trust"
"github.com/ory/x/contextx"
"github.com/ory/x/dbal"
"github.com/ory/x/networkx"
"github.com/ory/hydra/v2/jwk"
"github.com/ory/hydra/v2/driver"
"github.com/ory/hydra/v2/internal"
)
func init() {
pop.SetNowFunc(func() time.Time {
return time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
})
}
func testRegistry(t *testing.T, ctx context.Context, k string, t1 driver.Registry, t2 driver.Registry) {
t.Run("package=client/manager="+k, func(t *testing.T) {
t.Run("case=create-get-update-delete", client.TestHelperCreateGetUpdateDeleteClient(k, t1.Persister().Connection(context.Background()), t1.ClientManager(), t2.ClientManager()))
t.Run("case=autogenerate-key", client.TestHelperClientAutoGenerateKey(k, t1.ClientManager()))
t.Run("case=auth-client", client.TestHelperClientAuthenticate(k, t1.ClientManager()))
t.Run("case=update-two-clients", client.TestHelperUpdateTwoClients(k, t1.ClientManager()))
})
parallel := true
if k == "memory" || k == "mysql" || k == "cockroach" { // TODO enable parallel tests for cockroach once we configure the cockroach integration test server to support retry
parallel = false
}
t.Run("package=consent/manager="+k, consent.ManagerTests(t1, t1.ConsentManager(), t1.ClientManager(), t1.OAuth2Storage(), "t1", parallel))
t.Run("package=consent/manager="+k, consent.ManagerTests(t2, t2.ConsentManager(), t2.ClientManager(), t2.OAuth2Storage(), "t2", parallel))
t.Run("parallel-boundary", func(t *testing.T) {
t.Run("package=consent/janitor="+k, testhelpers.JanitorTests(t1, "t1", parallel))
t.Run("package=consent/janitor="+k, testhelpers.JanitorTests(t2, "t2", parallel))
})
t.Run("package=jwk/manager="+k, func(t *testing.T) {
for _, tc := range []struct {
alg string
skip bool
}{
{alg: "RS256", skip: false},
{alg: "ES256", skip: false},
{alg: "ES512", skip: false},
{alg: "HS256", skip: true},
{alg: "HS512", skip: true},
{alg: "EdDSA", skip: t1.Config().HSMEnabled()},
} {
t.Run("key_generator="+tc.alg, func(t *testing.T) {
if tc.skip {
t.Skipf("Skipping test. Not applicable for alg: %s", tc.alg)
}
if t1.Config().HSMEnabled() {
t.Run("TestManagerGenerateAndPersistKeySet", jwk.TestHelperManagerGenerateAndPersistKeySet(t1.KeyManager(), tc.alg, false))
// We don't support NID isolation with HSM at the moment
// t.Run("TestManagerGenerateAndPersistKeySet", jwk.TestHelperManagerNIDIsolationKeySet(t1.KeyManager(), t2.KeyManager(), tc.alg))
} else {
kid, err := uuid.NewV4()
require.NoError(t, err)
ks, err := jwk.GenerateJWK(context.Background(), jose.SignatureAlgorithm(tc.alg), kid.String(), "sig")
require.NoError(t, err)
t.Run("TestManagerKey", jwk.TestHelperManagerKey(t1.KeyManager(), tc.alg, ks, kid.String()))
t.Run("Parallel", func(t *testing.T) {
t.Run("TestManagerKeySet", jwk.TestHelperManagerKeySet(t1.KeyManager(), tc.alg, ks, kid.String(), parallel))
t.Run("TestManagerKeySet", jwk.TestHelperManagerKeySet(t2.KeyManager(), tc.alg, ks, kid.String(), parallel))
})
t.Run("Parallel", func(t *testing.T) {
t.Run("TestManagerGenerateAndPersistKeySet", jwk.TestHelperManagerGenerateAndPersistKeySet(t1.KeyManager(), tc.alg, parallel))
t.Run("TestManagerGenerateAndPersistKeySet", jwk.TestHelperManagerGenerateAndPersistKeySet(t2.KeyManager(), tc.alg, parallel))
})
}
})
}
t.Run("TestManagerGenerateAndPersistKeySetWithUnsupportedKeyGenerator", func(t *testing.T) {
_, err := t1.KeyManager().GenerateAndPersistKeySet(context.TODO(), "foo", "bar", "UNKNOWN", "sig")
require.Error(t, err)
assert.IsType(t, errors.WithStack(jwk.ErrUnsupportedKeyAlgorithm), err)
})
})
t.Run("package=grant/trust/manager="+k, func(t *testing.T) {
t.Run("parallel-boundary", func(t *testing.T) {
t.Run("case=create-get-delete/network=t1", trust.TestHelperGrantManagerCreateGetDeleteGrant(t1.GrantManager(), t1.KeyManager(), parallel))
t.Run("case=create-get-delete/network=t2", trust.TestHelperGrantManagerCreateGetDeleteGrant(t2.GrantManager(), t2.KeyManager(), parallel))
})
t.Run("parallel-boundary", func(t *testing.T) {
t.Run("case=errors", trust.TestHelperGrantManagerErrors(t1.GrantManager(), t1.KeyManager(), parallel))
t.Run("case=errors", trust.TestHelperGrantManagerErrors(t2.GrantManager(), t2.KeyManager(), parallel))
})
})
}
func TestManagersNextGen(t *testing.T) {
regs := map[string]driver.Registry{
"memory": internal.NewRegistrySQLFromURL(t, dbal.NewSQLiteTestDatabase(t), true, &contextx.Default{}),
}
if !testing.Short() {
regs["postgres"], regs["mysql"], regs["cockroach"], _ = internal.ConnectDatabases(t, true, &contextx.Default{})
}
ctx := context.Background()
networks := make([]uuid.UUID, 5)
for k := range networks {
nid := uuid.Must(uuid.NewV4())
for k := range regs {
require.NoError(t, regs[k].Persister().Connection(ctx).Create(&networkx.Network{ID: nid}))
}
networks[k] = nid
}
for k := range regs {
regs[k].WithContextualizer(new(contextx.TestContextualizer))
}
for k := range regs {
k := k
t.Run("database="+k, func(t *testing.T) {
t.Parallel()
client.TestHelperCreateGetUpdateDeleteClientNext(t, regs[k].Persister(), networks)
})
}
}
func TestManagers(t *testing.T) {
ctx := context.TODO()
t1registries := map[string]driver.Registry{
"memory": internal.NewRegistrySQLFromURL(t, dbal.NewSQLiteTestDatabase(t), true, &contextx.Default{}),
}
t2registries := map[string]driver.Registry{
"memory": internal.NewRegistrySQLFromURL(t, dbal.NewSQLiteTestDatabase(t), false, &contextx.Default{}),
}
if !testing.Short() {
t2registries["postgres"], t2registries["mysql"], t2registries["cockroach"], _ = internal.ConnectDatabases(t, false, &contextx.Default{})
t1registries["postgres"], t1registries["mysql"], t1registries["cockroach"], _ = internal.ConnectDatabases(t, true, &contextx.Default{})
}
network1NID, _ := uuid.NewV4()
network2NID, _ := uuid.NewV4()
for k, t1 := range t1registries {
t2 := t2registries[k]
require.NoError(t, t1.Persister().Connection(ctx).Create(&networkx.Network{ID: network1NID}))
require.NoError(t, t2.Persister().Connection(ctx).Create(&networkx.Network{ID: network2NID}))
t1.WithContextualizer(&contextx.Static{NID: network1NID, C: t1.Config().Source(context.Background())})
t2.WithContextualizer(&contextx.Static{NID: network2NID, C: t2.Config().Source(context.Background())})
t.Run("parallel-boundary", func(t *testing.T) { testRegistry(t, ctx, k, t1, t2) })
}
for k, t1 := range t1registries {
t2 := t2registries[k]
t2.WithContextualizer(&contextx.Static{NID: uuid.Nil, C: t2.Config().Source(context.Background())})
if !t1.Config().HSMEnabled() { // We don't support NID isolation with HSM at the moment
t.Run("package=jwk/manager="+k+"/case=nid",
jwk.TestHelperNID(t1.KeyManager(), t2.KeyManager()),
)
}
t.Run("package=consent/manager="+k+"/case=nid",
consent.TestHelperNID(t1, t1.ConsentManager(), t2.ConsentManager()),
)
}
} |
Go | hydra/persistence/sql/migratest/assertion_helpers.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package migratest
import (
"testing"
"time"
"github.com/gofrs/uuid"
"github.com/stretchr/testify/require"
"github.com/ory/hydra/v2/flow"
testhelpersuuid "github.com/ory/hydra/v2/internal/testhelpers/uuid"
"github.com/ory/x/sqlxx"
)
func fixturizeFlow(t *testing.T, f *flow.Flow) {
testhelpersuuid.AssertUUID(t, &f.NID)
f.NID = uuid.Nil
require.NotZero(t, f.ClientID)
f.ClientID = ""
require.NotNil(t, f.Client)
f.Client = nil
recently := time.Now().Add(-time.Minute)
require.Greater(t, time.Time(f.LoginInitializedAt).UnixNano(), recently.UnixNano())
f.LoginInitializedAt = sqlxx.NullTime{}
require.True(t, f.RequestedAt.After(recently))
f.RequestedAt = time.Time{}
require.True(t, time.Time(f.LoginAuthenticatedAt).After(recently))
f.LoginAuthenticatedAt = sqlxx.NullTime{}
f.ConsentHandledAt = sqlxx.NullTime{}
} |
Go | hydra/persistence/sql/migratest/migration_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package migratest
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/ory/hydra/v2/internal"
"github.com/ory/x/contextx"
"github.com/bradleyjkemp/cupaloy/v2"
"github.com/fatih/structs"
"github.com/gofrs/uuid"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/gobuffalo/pop/v6"
"github.com/ory/x/logrusx"
"github.com/ory/x/networkx"
"github.com/ory/x/sqlxx"
"github.com/ory/hydra/v2/flow"
testhelpersuuid "github.com/ory/hydra/v2/internal/testhelpers/uuid"
"github.com/ory/hydra/v2/persistence/sql"
"github.com/ory/x/popx"
"github.com/ory/x/sqlcon/dockertest"
"github.com/stretchr/testify/require"
"github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/consent"
"github.com/ory/hydra/v2/jwk"
"github.com/ory/hydra/v2/oauth2"
"github.com/ory/hydra/v2/x"
)
func snapshotFor(paths ...string) *cupaloy.Config {
return cupaloy.New(
cupaloy.CreateNewAutomatically(true),
cupaloy.FailOnUpdate(true),
cupaloy.SnapshotFileExtension(".json"),
cupaloy.SnapshotSubdirectory(filepath.Join(paths...)),
)
}
func CompareWithFixture(t *testing.T, actual interface{}, prefix string, id string) {
s := snapshotFor("fixtures", prefix)
actualJSON, err := json.MarshalIndent(actual, "", " ")
require.NoError(t, err)
assert.NoError(t, s.SnapshotWithName(id, actualJSON))
}
func TestMigrations(t *testing.T) {
connections := make(map[string]*pop.Connection, 1)
if testing.Short() {
reg := internal.NewMockedRegistry(t, &contextx.Default{})
require.NoError(t, reg.Persister().MigrateUp(context.Background()))
c := reg.Persister().Connection(context.Background())
connections["sqlite"] = c
}
if !testing.Short() {
dockertest.Parallel([]func(){
func() {
connections["postgres"] = dockertest.ConnectToTestPostgreSQLPop(t)
},
func() {
connections["mysql"] = dockertest.ConnectToTestMySQLPop(t)
},
func() {
connections["cockroach"] = dockertest.ConnectToTestCockroachDBPop(t)
},
})
}
var test = func(db string, c *pop.Connection) func(t *testing.T) {
return func(t *testing.T) {
ctx := context.Background()
x.CleanSQLPop(t, c)
l := logrusx.New("", "", logrusx.ForceLevel(logrus.DebugLevel))
tm, err := popx.NewMigrationBox(
os.DirFS("../migrations"),
popx.NewMigrator(c, l, nil, 1*time.Minute),
popx.WithTestdata(t, os.DirFS("./testdata")))
require.NoError(t, err)
require.NoError(t, tm.Up(ctx))
t.Run("suite=fixtures", func(t *testing.T) {
t.Run("case=hydra_client", func(t *testing.T) {
cs := []client.Client{}
require.NoError(t, c.All(&cs))
require.Equal(t, 18, len(cs))
for _, c := range cs {
require.False(t, c.CreatedAt.IsZero())
require.False(t, c.UpdatedAt.IsZero())
c.CreatedAt = time.Time{} // Some CreatedAt and UpdatedAt values are generated during migrations so we zero them in the fixtures
c.UpdatedAt = time.Time{}
testhelpersuuid.AssertUUID(t, &c.ID)
testhelpersuuid.AssertUUID(t, &c.NID)
c.ID = uuid.Nil
c.NID = uuid.Nil
CompareWithFixture(t, structs.Map(c), "hydra_client", c.LegacyClientID)
}
})
t.Run("case=hydra_jwk", func(t *testing.T) {
js := []jwk.SQLData{}
require.NoError(t, c.All(&js))
require.Equal(t, 7, len(js))
for _, j := range js {
testhelpersuuid.AssertUUID(t, &j.ID)
testhelpersuuid.AssertUUID(t, &j.NID)
j.ID = uuid.Nil // Some IDs are generated at migration time so we zero them in the fixtures
j.NID = uuid.Nil
require.False(t, j.CreatedAt.IsZero())
j.CreatedAt = time.Time{}
CompareWithFixture(t, j, "hydra_jwk", j.KID)
}
})
flows := []flow.Flow{}
require.NoError(t, c.All(&flows))
require.Equal(t, 17, len(flows))
t.Run("case=hydra_oauth2_flow", func(t *testing.T) {
for _, f := range flows {
fixturizeFlow(t, &f)
CompareWithFixture(t, f, "hydra_oauth2_flow", f.ID)
}
})
t.Run("case=hydra_oauth2_authentication_session", func(t *testing.T) {
ss := []flow.LoginSession{}
c.All(&ss)
require.Equal(t, 17, len(ss))
for _, s := range ss {
testhelpersuuid.AssertUUID(t, &s.NID)
s.NID = uuid.Nil
s.AuthenticatedAt = sqlxx.NullTime(time.Time{})
CompareWithFixture(t, s, "hydra_oauth2_authentication_session", s.ID)
}
})
t.Run("case=hydra_oauth2_obfuscated_authentication_session", func(t *testing.T) {
ss := []consent.ForcedObfuscatedLoginSession{}
c.All(&ss)
require.Equal(t, 13, len(ss))
for _, s := range ss {
testhelpersuuid.AssertUUID(t, &s.NID)
s.NID = uuid.Nil
CompareWithFixture(t, s, "hydra_oauth2_obfuscated_authentication_session", fmt.Sprintf("%s_%s", s.Subject, s.ClientID))
}
})
t.Run("case=hydra_oauth2_logout_request", func(t *testing.T) {
lrs := []flow.LogoutRequest{}
c.All(&lrs)
require.Equal(t, 6, len(lrs))
for _, s := range lrs {
testhelpersuuid.AssertUUID(t, &s.NID)
s.NID = uuid.Nil
s.Client = nil
CompareWithFixture(t, s, "hydra_oauth2_logout_request", s.ID)
}
})
t.Run("case=hydra_oauth2_jti_blacklist", func(t *testing.T) {
bjtis := []oauth2.BlacklistedJTI{}
c.All(&bjtis)
require.Equal(t, 1, len(bjtis))
for _, bjti := range bjtis {
testhelpersuuid.AssertUUID(t, &bjti.NID)
bjti.NID = uuid.Nil
bjti.Expiry = time.Time{}
CompareWithFixture(t, bjti, "hydra_oauth2_jti_blacklist", bjti.ID)
}
})
t.Run("case=hydra_oauth2_access", func(t *testing.T) {
as := []sql.OAuth2RequestSQL{}
c.RawQuery("SELECT * FROM hydra_oauth2_access").All(&as)
require.Equal(t, 13, len(as))
for _, a := range as {
testhelpersuuid.AssertUUID(t, &a.NID)
a.NID = uuid.Nil
require.False(t, a.RequestedAt.IsZero())
a.RequestedAt = time.Time{}
require.NotZero(t, a.Client)
a.Client = ""
CompareWithFixture(t, a, "hydra_oauth2_access", a.ID)
}
})
t.Run("case=hydra_oauth2_refresh", func(t *testing.T) {
rs := []sql.OAuth2RequestSQL{}
c.RawQuery("SELECT * FROM hydra_oauth2_refresh").All(&rs)
require.Equal(t, 13, len(rs))
for _, r := range rs {
testhelpersuuid.AssertUUID(t, &r.NID)
r.NID = uuid.Nil
require.False(t, r.RequestedAt.IsZero())
r.RequestedAt = time.Time{}
require.NotZero(t, r.Client)
r.Client = ""
CompareWithFixture(t, r, "hydra_oauth2_refresh", r.ID)
}
})
t.Run("case=hydra_oauth2_code", func(t *testing.T) {
cs := []sql.OAuth2RequestSQL{}
c.RawQuery("SELECT * FROM hydra_oauth2_code").All(&cs)
require.Equal(t, 13, len(cs))
for _, c := range cs {
testhelpersuuid.AssertUUID(t, &c.NID)
c.NID = uuid.Nil
require.False(t, c.RequestedAt.IsZero())
c.RequestedAt = time.Time{}
require.NotZero(t, c.Client)
c.Client = ""
CompareWithFixture(t, c, "hydra_oauth2_code", c.ID)
}
})
t.Run("case=hydra_oauth2_oidc", func(t *testing.T) {
os := []sql.OAuth2RequestSQL{}
c.RawQuery("SELECT * FROM hydra_oauth2_oidc").All(&os)
require.Equal(t, 13, len(os))
for _, o := range os {
testhelpersuuid.AssertUUID(t, &o.NID)
o.NID = uuid.Nil
require.False(t, o.RequestedAt.IsZero())
o.RequestedAt = time.Time{}
require.NotZero(t, o.Client)
o.Client = ""
CompareWithFixture(t, o, "hydra_oauth2_oidc", o.ID)
}
})
t.Run("case=hydra_oauth2_pkce", func(t *testing.T) {
ps := []sql.OAuth2RequestSQL{}
c.RawQuery("SELECT * FROM hydra_oauth2_pkce").All(&ps)
require.Equal(t, 11, len(ps))
for _, p := range ps {
testhelpersuuid.AssertUUID(t, &p.NID)
p.NID = uuid.Nil
require.False(t, p.RequestedAt.IsZero())
p.RequestedAt = time.Time{}
require.NotZero(t, p.Client)
p.Client = ""
CompareWithFixture(t, p, "hydra_oauth2_pkce", p.ID)
}
})
t.Run("case=networks", func(t *testing.T) {
ns := []networkx.Network{}
c.RawQuery("SELECT * FROM networks").All(&ns)
require.Equal(t, 1, len(ns))
for _, n := range ns {
testhelpersuuid.AssertUUID(t, &n.ID)
require.NotZero(t, n.CreatedAt)
require.NotZero(t, n.UpdatedAt)
}
})
})
}
}
for db, c := range connections {
t.Run(fmt.Sprintf("database=%s", db), test(db, c))
x.CleanSQLPop(t, c)
require.NoError(t, c.Close())
}
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-0001.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [],
"Audience": [],
"BackChannelLogoutSessionRequired": false,
"BackChannelLogoutURI": "",
"ClientURI": "http://client/0001",
"Contacts": [
"contact-0001_1"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": false,
"FrontChannelLogoutURI": "",
"GrantTypes": [
"grant-0001_1"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "",
"LegacyClientID": "client-0001",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
}
},
"LogoURI": "http://logo/0001",
"Metadata": {},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 0001",
"Owner": "owner-0001",
"PKDeprecated": 1,
"PolicyURI": "http://policy/0001",
"PostLogoutRedirectURIs": [],
"RedirectURIs": [
"http://redirect/0001_1"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "",
"RequestURIs": [],
"ResponseTypes": [
"response-0001_1"
],
"Scope": "scope-0001",
"Secret": "secret-0001",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "",
"SkipConsent": false,
"SubjectType": "",
"TermsOfServiceURI": "http://tos/0001",
"TokenEndpointAuthMethod": "none",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": ""
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-0002.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [],
"Audience": [],
"BackChannelLogoutSessionRequired": false,
"BackChannelLogoutURI": "",
"ClientURI": "http://client/0002",
"Contacts": [
"contact-0002_1"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": false,
"FrontChannelLogoutURI": "",
"GrantTypes": [
"grant-0002_1"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "",
"LegacyClientID": "client-0002",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
}
},
"LogoURI": "http://logo/0002",
"Metadata": {},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 0002",
"Owner": "owner-0002",
"PKDeprecated": 2,
"PolicyURI": "http://policy/0002",
"PostLogoutRedirectURIs": [],
"RedirectURIs": [
"http://redirect/0002_1"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "",
"RequestURIs": [],
"ResponseTypes": [
"response-0002_1"
],
"Scope": "scope-0002",
"Secret": "secret-0002",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "",
"SkipConsent": false,
"SubjectType": "",
"TermsOfServiceURI": "http://tos/0002",
"TokenEndpointAuthMethod": "none",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": ""
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-0003.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [],
"Audience": [],
"BackChannelLogoutSessionRequired": false,
"BackChannelLogoutURI": "",
"ClientURI": "http://client/0003",
"Contacts": [
"contact-0003_1"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": false,
"FrontChannelLogoutURI": "",
"GrantTypes": [
"grant-0003_1"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "",
"LegacyClientID": "client-0003",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
}
},
"LogoURI": "http://logo/0003",
"Metadata": {},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 0003",
"Owner": "owner-0003",
"PKDeprecated": 3,
"PolicyURI": "http://policy/0003",
"PostLogoutRedirectURIs": [],
"RedirectURIs": [
"http://redirect/0003_1"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "r_alg-0003",
"RequestURIs": [],
"ResponseTypes": [
"response-0003_1"
],
"Scope": "scope-0003",
"Secret": "secret-0003",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "",
"SkipConsent": false,
"SubjectType": "",
"TermsOfServiceURI": "http://tos/0003",
"TokenEndpointAuthMethod": "none",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": "u_alg-0003"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-0004.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [],
"Audience": [],
"BackChannelLogoutSessionRequired": false,
"BackChannelLogoutURI": "",
"ClientURI": "http://client/0004",
"Contacts": [
"contact-0004_1"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": false,
"FrontChannelLogoutURI": "",
"GrantTypes": [
"grant-0004_1"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "http://jwks/0004",
"LegacyClientID": "client-0004",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
}
},
"LogoURI": "http://logo/0004",
"Metadata": {},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 0004",
"Owner": "owner-0004",
"PKDeprecated": 4,
"PolicyURI": "http://policy/0004",
"PostLogoutRedirectURIs": [],
"RedirectURIs": [
"http://redirect/0004_1"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "r_alg-0004",
"RequestURIs": [
"http://request/0004_1"
],
"ResponseTypes": [
"response-0004_1"
],
"Scope": "scope-0004",
"Secret": "secret-0004",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "http://sector_id/0004",
"SkipConsent": false,
"SubjectType": "",
"TermsOfServiceURI": "http://tos/0004",
"TokenEndpointAuthMethod": "none",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": "u_alg-0004"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-0005.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [],
"Audience": [],
"BackChannelLogoutSessionRequired": false,
"BackChannelLogoutURI": "",
"ClientURI": "http://client/0005",
"Contacts": [
"contact-0005_1"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": false,
"FrontChannelLogoutURI": "",
"GrantTypes": [
"grant-0005_1"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "http://jwks/0005",
"LegacyClientID": "client-0005",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
}
},
"LogoURI": "http://logo/0005",
"Metadata": {},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 0005",
"Owner": "owner-0005",
"PKDeprecated": 5,
"PolicyURI": "http://policy/0005",
"PostLogoutRedirectURIs": [],
"RedirectURIs": [
"http://redirect/0005_1"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "r_alg-0005",
"RequestURIs": [
"http://request/0005_1"
],
"ResponseTypes": [
"response-0005_1"
],
"Scope": "scope-0005",
"Secret": "secret-0005",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "http://sector_id/0005",
"SkipConsent": false,
"SubjectType": "",
"TermsOfServiceURI": "http://tos/0005",
"TokenEndpointAuthMethod": "token_auth-0005",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": "u_alg-0005"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-0006.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [],
"Audience": [],
"BackChannelLogoutSessionRequired": false,
"BackChannelLogoutURI": "",
"ClientURI": "http://client/0006",
"Contacts": [
"contact-0006_1"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": false,
"FrontChannelLogoutURI": "",
"GrantTypes": [
"grant-0006_1"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "http://jwks/0006",
"LegacyClientID": "client-0006",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
}
},
"LogoURI": "http://logo/0006",
"Metadata": {},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 0006",
"Owner": "owner-0006",
"PKDeprecated": 6,
"PolicyURI": "http://policy/0006",
"PostLogoutRedirectURIs": [],
"RedirectURIs": [
"http://redirect/0006_1"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "r_alg-0006",
"RequestURIs": [
"http://request/0006_1"
],
"ResponseTypes": [
"response-0006_1"
],
"Scope": "scope-0006",
"Secret": "secret-0006",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "http://sector_id/0006",
"SkipConsent": false,
"SubjectType": "subject-0006",
"TermsOfServiceURI": "http://tos/0006",
"TokenEndpointAuthMethod": "token_auth-0006",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": "u_alg-0006"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-0007.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [],
"Audience": [],
"BackChannelLogoutSessionRequired": false,
"BackChannelLogoutURI": "",
"ClientURI": "http://client/0007",
"Contacts": [
"contact-0007_1"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": false,
"FrontChannelLogoutURI": "",
"GrantTypes": [
"grant-0007_1"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "http://jwks/0007",
"LegacyClientID": "client-0007",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
}
},
"LogoURI": "http://logo/0007",
"Metadata": {},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 0007",
"Owner": "owner-0007",
"PKDeprecated": 7,
"PolicyURI": "http://policy/0007",
"PostLogoutRedirectURIs": [],
"RedirectURIs": [
"http://redirect/0007_1"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "r_alg-0007",
"RequestURIs": [
"http://request/0007_1"
],
"ResponseTypes": [
"response-0007_1"
],
"Scope": "scope-0007",
"Secret": "secret-0007",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "http://sector_id/0007",
"SkipConsent": false,
"SubjectType": "subject-0007",
"TermsOfServiceURI": "http://tos/0007",
"TokenEndpointAuthMethod": "token_auth-0007",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": "u_alg-0007"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-0008.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [
"http://cors/0008_1"
],
"Audience": [],
"BackChannelLogoutSessionRequired": false,
"BackChannelLogoutURI": "",
"ClientURI": "http://client/0008",
"Contacts": [
"contact-0008_1"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": false,
"FrontChannelLogoutURI": "",
"GrantTypes": [
"grant-0008_1"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "http://jwks/0008",
"LegacyClientID": "client-0008",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
}
},
"LogoURI": "http://logo/0008",
"Metadata": {},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 0008",
"Owner": "owner-0008",
"PKDeprecated": 8,
"PolicyURI": "http://policy/0008",
"PostLogoutRedirectURIs": [],
"RedirectURIs": [
"http://redirect/0008_1"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "r_alg-0008",
"RequestURIs": [
"http://request/0008_1"
],
"ResponseTypes": [
"response-0008_1"
],
"Scope": "scope-0008",
"Secret": "secret-0008",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "http://sector_id/0008",
"SkipConsent": false,
"SubjectType": "subject-0008",
"TermsOfServiceURI": "http://tos/0008",
"TokenEndpointAuthMethod": "token_auth-0008",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": "u_alg-0008"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-0009.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [
"http://cors/0009_1"
],
"Audience": [],
"BackChannelLogoutSessionRequired": false,
"BackChannelLogoutURI": "",
"ClientURI": "http://client/0009",
"Contacts": [
"contact-0009_1"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": false,
"FrontChannelLogoutURI": "",
"GrantTypes": [
"grant-0009_1"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "http://jwks/0009",
"LegacyClientID": "client-0009",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
}
},
"LogoURI": "http://logo/0009",
"Metadata": {},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 0009",
"Owner": "owner-0009",
"PKDeprecated": 9,
"PolicyURI": "http://policy/0009",
"PostLogoutRedirectURIs": [],
"RedirectURIs": [
"http://redirect/0009_1"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "r_alg-0009",
"RequestURIs": [
"http://request/0009_1"
],
"ResponseTypes": [
"response-0009_1"
],
"Scope": "scope-0009",
"Secret": "secret-0009",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "http://sector_id/0009",
"SkipConsent": false,
"SubjectType": "subject-0009",
"TermsOfServiceURI": "http://tos/0009",
"TokenEndpointAuthMethod": "token_auth-0009",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": "u_alg-0009"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-0010.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [
"http://cors/0010_1"
],
"Audience": [],
"BackChannelLogoutSessionRequired": false,
"BackChannelLogoutURI": "",
"ClientURI": "http://client/0010",
"Contacts": [
"contact-0010_1"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": false,
"FrontChannelLogoutURI": "",
"GrantTypes": [
"grant-0010_1"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "http://jwks/0010",
"LegacyClientID": "client-0010",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
}
},
"LogoURI": "http://logo/0010",
"Metadata": {},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 0010",
"Owner": "owner-0010",
"PKDeprecated": 10,
"PolicyURI": "http://policy/0010",
"PostLogoutRedirectURIs": [],
"RedirectURIs": [
"http://redirect/0010_1"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "r_alg-0010",
"RequestURIs": [
"http://request/0010_1"
],
"ResponseTypes": [
"response-0010_1"
],
"Scope": "scope-0010",
"Secret": "secret-0010",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "http://sector_id/0010",
"SkipConsent": false,
"SubjectType": "subject-0010",
"TermsOfServiceURI": "http://tos/0010",
"TokenEndpointAuthMethod": "token_auth-0010",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": "u_alg-0010"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-0011.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [
"http://cors/0011_1"
],
"Audience": [
"autdience-0011_1"
],
"BackChannelLogoutSessionRequired": false,
"BackChannelLogoutURI": "",
"ClientURI": "http://client/0011",
"Contacts": [
"contact-0011_1"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": false,
"FrontChannelLogoutURI": "",
"GrantTypes": [
"grant-0011_1"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "http://jwks/0011",
"LegacyClientID": "client-0011",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
}
},
"LogoURI": "http://logo/0011",
"Metadata": {},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 0011",
"Owner": "owner-0011",
"PKDeprecated": 11,
"PolicyURI": "http://policy/0011",
"PostLogoutRedirectURIs": [],
"RedirectURIs": [
"http://redirect/0011_1"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "r_alg-0011",
"RequestURIs": [
"http://request/0011_1"
],
"ResponseTypes": [
"response-0011_1"
],
"Scope": "scope-0011",
"Secret": "secret-0011",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "http://sector_id/0011",
"SkipConsent": false,
"SubjectType": "subject-0011",
"TermsOfServiceURI": "http://tos/0011",
"TokenEndpointAuthMethod": "token_auth-0011",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": "u_alg-0011"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-0012.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [
"http://cors/0012_1"
],
"Audience": [
"autdience-0012_1"
],
"BackChannelLogoutSessionRequired": false,
"BackChannelLogoutURI": "",
"ClientURI": "http://client/0012",
"Contacts": [
"contact-0012_1"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": false,
"FrontChannelLogoutURI": "",
"GrantTypes": [
"grant-0012_1"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "http://jwks/0012",
"LegacyClientID": "client-0012",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
}
},
"LogoURI": "http://logo/0012",
"Metadata": {},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 0012",
"Owner": "owner-0012",
"PKDeprecated": 12,
"PolicyURI": "http://policy/0012",
"PostLogoutRedirectURIs": [],
"RedirectURIs": [
"http://redirect/0012_1"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "r_alg-0012",
"RequestURIs": [
"http://request/0012_1"
],
"ResponseTypes": [
"response-0012_1"
],
"Scope": "scope-0012",
"Secret": "secret-0012",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "http://sector_id/0012",
"SkipConsent": false,
"SubjectType": "subject-0012",
"TermsOfServiceURI": "http://tos/0012",
"TokenEndpointAuthMethod": "token_auth-0012",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": "u_alg-0012"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-0013.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [
"http://cors/0013_1"
],
"Audience": [
"autdience-0013_1"
],
"BackChannelLogoutSessionRequired": true,
"BackChannelLogoutURI": "http://back_logout/0013",
"ClientURI": "http://client/0013",
"Contacts": [
"contact-0013_1"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": true,
"FrontChannelLogoutURI": "http://front_logout/0013",
"GrantTypes": [
"grant-0013_1"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "http://jwks/0013",
"LegacyClientID": "client-0013",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
}
},
"LogoURI": "http://logo/0013",
"Metadata": {},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 0013",
"Owner": "owner-0013",
"PKDeprecated": 13,
"PolicyURI": "http://policy/0013",
"PostLogoutRedirectURIs": [
"http://post_redirect/0013_1"
],
"RedirectURIs": [
"http://redirect/0013_1"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "r_alg-0013",
"RequestURIs": [
"http://request/0013_1"
],
"ResponseTypes": [
"response-0013_1"
],
"Scope": "scope-0013",
"Secret": "secret-0013",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "http://sector_id/0013",
"SkipConsent": false,
"SubjectType": "subject-0013",
"TermsOfServiceURI": "http://tos/0013",
"TokenEndpointAuthMethod": "token_auth-0013",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": "u_alg-0013"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-0014.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [
"http://cors/0014_1"
],
"Audience": [
"autdience-0014_1"
],
"BackChannelLogoutSessionRequired": true,
"BackChannelLogoutURI": "http://back_logout/0014",
"ClientURI": "http://client/0014",
"Contacts": [
"contact-0014_1"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": true,
"FrontChannelLogoutURI": "http://front_logout/0014",
"GrantTypes": [
"grant-0014_1"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "http://jwks/0014",
"LegacyClientID": "client-0014",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
}
},
"LogoURI": "http://logo/0014",
"Metadata": {
"migration": "0014"
},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 0014",
"Owner": "owner-0014",
"PKDeprecated": 14,
"PolicyURI": "http://policy/0014",
"PostLogoutRedirectURIs": [
"http://post_redirect/0014_1"
],
"RedirectURIs": [
"http://redirect/0014_1"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "r_alg-0014",
"RequestURIs": [
"http://request/0014_1"
],
"ResponseTypes": [
"response-0014_1"
],
"Scope": "scope-0014",
"Secret": "secret-0014",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "http://sector_id/0014",
"SkipConsent": false,
"SubjectType": "subject-0014",
"TermsOfServiceURI": "http://tos/0014",
"TokenEndpointAuthMethod": "token_auth-0014",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": "u_alg-0014"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-0015.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [
"http://cors/0015_1"
],
"Audience": [
"autdience-0015_1"
],
"BackChannelLogoutSessionRequired": true,
"BackChannelLogoutURI": "http://back_logout/0015",
"ClientURI": "http://client/0015",
"Contacts": [
"contact-0015_1"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": true,
"FrontChannelLogoutURI": "http://front_logout/0015",
"GrantTypes": [
"grant-0015_1"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "http://jwks/0015",
"LegacyClientID": "client-0015",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 151000000000,
"Valid": true
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 152000000000,
"Valid": true
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 153000000000,
"Valid": true
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 154000000000,
"Valid": true
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 155000000000,
"Valid": true
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 156000000000,
"Valid": true
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 157000000000,
"Valid": true
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 158000000000,
"Valid": true
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 159000000000,
"Valid": true
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 161000000000,
"Valid": true
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 160000000000,
"Valid": true
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 162000000000,
"Valid": true
}
},
"LogoURI": "http://logo/0015",
"Metadata": {
"migration": "0015"
},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 0015",
"Owner": "owner-0015",
"PKDeprecated": 15,
"PolicyURI": "http://policy/0015",
"PostLogoutRedirectURIs": [
"http://post_redirect/0015_1"
],
"RedirectURIs": [
"http://redirect/0015_1"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "r_alg-0015",
"RequestURIs": [
"http://request/0015_1"
],
"ResponseTypes": [
"response-0015_1"
],
"Scope": "scope-0015",
"Secret": "secret-0015",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "http://sector_id/0015",
"SkipConsent": false,
"SubjectType": "subject-0015",
"TermsOfServiceURI": "http://tos/0015",
"TokenEndpointAuthMethod": "token_auth-0015",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": "u_alg-0015"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-20.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [
"http://cors/20_1"
],
"Audience": [
"autdience-20_1"
],
"BackChannelLogoutSessionRequired": true,
"BackChannelLogoutURI": "http://back_logout/20",
"ClientURI": "http://client/20",
"Contacts": [
"contact-20_1"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": true,
"FrontChannelLogoutURI": "http://front_logout/20",
"GrantTypes": [
"grant-20_1"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "http://jwks/20",
"LegacyClientID": "client-20",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
}
},
"LogoURI": "http://logo/20",
"Metadata": {
"migration": "20"
},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 20",
"Owner": "owner-20",
"PKDeprecated": 0,
"PolicyURI": "http://policy/20",
"PostLogoutRedirectURIs": [
"http://post_redirect/20_1"
],
"RedirectURIs": [
"http://redirect/20_1"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "r_alg-20",
"RequestURIs": [
"http://request/20_1"
],
"ResponseTypes": [
"response-20_1"
],
"Scope": "scope-20",
"Secret": "secret-20",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "http://sector_id/20",
"SkipConsent": false,
"SubjectType": "subject-20",
"TermsOfServiceURI": "http://tos/20",
"TokenEndpointAuthMethod": "token_auth-20",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": "u_alg-20"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-2005.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [
"http://cors/2005_1"
],
"Audience": [
"autdience-2005_1"
],
"BackChannelLogoutSessionRequired": true,
"BackChannelLogoutURI": "http://back_logout/2005",
"ClientURI": "http://client/2005",
"Contacts": [
"contact-2005_1"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": true,
"FrontChannelLogoutURI": "http://front_logout/2005",
"GrantTypes": [
"grant-2005_1"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "http://jwks/2005",
"LegacyClientID": "client-2005",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
}
},
"LogoURI": "http://logo/2005",
"Metadata": {
"migration": "2005"
},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 2005",
"Owner": "owner-2005",
"PKDeprecated": 2005,
"PolicyURI": "http://policy/2005",
"PostLogoutRedirectURIs": [
"http://post_redirect/2005_1"
],
"RedirectURIs": [
"http://redirect/2005_1"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "r_alg-2005",
"RequestURIs": [
"http://request/2005_1"
],
"ResponseTypes": [
"response-2005_1"
],
"Scope": "scope-2005",
"Secret": "secret-2005",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "http://sector_id/2005",
"SkipConsent": false,
"SubjectType": "subject-2005",
"TermsOfServiceURI": "http://tos/2005",
"TokenEndpointAuthMethod": "token_auth-2005",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": "u_alg-2005"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_client/client-21.json | {
"AccessTokenStrategy": "",
"AllowedCORSOrigins": [
"http://cors/21_1",
"http://cors/21_2"
],
"Audience": [
"autdience-21_1",
"autdience-21_2"
],
"BackChannelLogoutSessionRequired": true,
"BackChannelLogoutURI": "http://back_logout/21",
"ClientURI": "http://client/21",
"Contacts": [
"contact-21_1",
"contact-21_2"
],
"CreatedAt": "0001-01-01T00:00:00Z",
"FrontChannelLogoutSessionRequired": true,
"FrontChannelLogoutURI": "http://front_logout/21",
"GrantTypes": [
"grant-21_1",
"grant-21_2"
],
"ID": "00000000-0000-0000-0000-000000000000",
"JSONWebKeys": {
"JSONWebKeySet": null
},
"JSONWebKeysURI": "http://jwks/21",
"LegacyClientID": "client-21",
"Lifespans": {
"AuthorizationCodeGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"AuthorizationCodeGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ClientCredentialsGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"ImplicitGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"JwtBearerGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"PasswordGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantAccessTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantIDTokenLifespan": {
"Duration": 0,
"Valid": false
},
"RefreshTokenGrantRefreshTokenLifespan": {
"Duration": 0,
"Valid": false
}
},
"LogoURI": "http://logo/21",
"Metadata": {
"migration": "21"
},
"NID": "00000000-0000-0000-0000-000000000000",
"Name": "Client 21",
"Owner": "owner-21",
"PKDeprecated": 0,
"PolicyURI": "http://policy/21",
"PostLogoutRedirectURIs": [
"http://post_redirect/21_1",
"http://post_redirect/21_2"
],
"RedirectURIs": [
"http://redirect/21_1",
"http://redirect/21_2"
],
"RegistrationAccessToken": "",
"RegistrationAccessTokenSignature": "",
"RegistrationClientURI": "",
"RequestObjectSigningAlgorithm": "r_alg-21",
"RequestURIs": [
"http://request/21_1",
"http://request/21_2"
],
"ResponseTypes": [
"response-21_1",
"response-21_2"
],
"Scope": "scope-21",
"Secret": "secret-21",
"SecretExpiresAt": 0,
"SectorIdentifierURI": "http://sector_id/21",
"SkipConsent": false,
"SubjectType": "subject-21",
"TermsOfServiceURI": "http://tos/21",
"TokenEndpointAuthMethod": "token_auth-21",
"TokenEndpointAuthSigningAlgorithm": "",
"UpdatedAt": "0001-01-01T00:00:00Z",
"UserinfoSignedResponseAlg": "u_alg-21"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_jwk/kid-0001.json | {
"ID": "00000000-0000-0000-0000-000000000000",
"Set": "sid-0001",
"KID": "kid-0001",
"Version": 1,
"CreatedAt": "0001-01-01T00:00:00Z",
"Key": "key-0001"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_jwk/kid-0002.json | {
"ID": "00000000-0000-0000-0000-000000000000",
"Set": "sid-0002",
"KID": "kid-0002",
"Version": 2,
"CreatedAt": "0001-01-01T00:00:00Z",
"Key": "key-0002"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_jwk/kid-0003.json | {
"ID": "00000000-0000-0000-0000-000000000000",
"Set": "sid-0003",
"KID": "kid-0003",
"Version": 3,
"CreatedAt": "0001-01-01T00:00:00Z",
"Key": "key-0003"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_jwk/kid-0004.json | {
"ID": "00000000-0000-0000-0000-000000000000",
"Set": "sid-0004",
"KID": "kid-0004",
"Version": 4,
"CreatedAt": "0001-01-01T00:00:00Z",
"Key": "key-0004"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_jwk/kid-0005.json | {
"ID": "00000000-0000-0000-0000-000000000000",
"Set": "sid-0005",
"KID": "kid-0005",
"Version": 4,
"CreatedAt": "0001-01-01T00:00:00Z",
"Key": "key-0005"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_jwk/kid-0008.json | {
"ID": "00000000-0000-0000-0000-000000000000",
"Set": "sid-0008",
"KID": "kid-0008",
"Version": 2,
"CreatedAt": "0001-01-01T00:00:00Z",
"Key": "key-0002"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_jwk/kid-0009.json | {
"ID": "00000000-0000-0000-0000-000000000000",
"Set": "sid-0009",
"KID": "kid-0009",
"Version": 2,
"CreatedAt": "0001-01-01T00:00:00Z",
"Key": "key-0002"
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_oauth2_access/sig-0001.json | {
"ID": "sig-0001",
"NID": "00000000-0000-0000-0000-000000000000",
"Request": "req-0001",
"ConsentChallenge": {
"String": "",
"Valid": false
},
"RequestedAt": "0001-01-01T00:00:00Z",
"Client": "",
"Scopes": "scope-0001",
"GrantedScope": "granted_scope-0001",
"RequestedAudience": "",
"GrantedAudience": "",
"Form": "form_data-0001",
"Subject": "",
"Active": true,
"Session": "c2Vzc2lvbi0wMDAx",
"Table": ""
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_oauth2_access/sig-0002.json | {
"ID": "sig-0002",
"NID": "00000000-0000-0000-0000-000000000000",
"Request": "req-0002",
"ConsentChallenge": {
"String": "",
"Valid": false
},
"RequestedAt": "0001-01-01T00:00:00Z",
"Client": "",
"Scopes": "scope-0002",
"GrantedScope": "granted_scope-0002",
"RequestedAudience": "",
"GrantedAudience": "",
"Form": "form_data-0002",
"Subject": "subject-0002",
"Active": true,
"Session": "c2Vzc2lvbi0wMDAy",
"Table": ""
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_oauth2_access/sig-0003.json | {
"ID": "sig-0003",
"NID": "00000000-0000-0000-0000-000000000000",
"Request": "req-0003",
"ConsentChallenge": {
"String": "",
"Valid": false
},
"RequestedAt": "0001-01-01T00:00:00Z",
"Client": "",
"Scopes": "scope-0003",
"GrantedScope": "granted_scope-0003",
"RequestedAudience": "",
"GrantedAudience": "",
"Form": "form_data-0003",
"Subject": "subject-0003",
"Active": true,
"Session": "c2Vzc2lvbi0wMDAz",
"Table": ""
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_oauth2_access/sig-0004.json | {
"ID": "sig-0004",
"NID": "00000000-0000-0000-0000-000000000000",
"Request": "req-0004",
"ConsentChallenge": {
"String": "",
"Valid": false
},
"RequestedAt": "0001-01-01T00:00:00Z",
"Client": "",
"Scopes": "scope-0004",
"GrantedScope": "granted_scope-0004",
"RequestedAudience": "",
"GrantedAudience": "",
"Form": "form_data-0004",
"Subject": "subject-0004",
"Active": false,
"Session": "c2Vzc2lvbi0wMDA0",
"Table": ""
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_oauth2_access/sig-0005.json | {
"ID": "sig-0005",
"NID": "00000000-0000-0000-0000-000000000000",
"Request": "req-0005",
"ConsentChallenge": {
"String": "",
"Valid": false
},
"RequestedAt": "0001-01-01T00:00:00Z",
"Client": "",
"Scopes": "scope-0005",
"GrantedScope": "granted_scope-0005",
"RequestedAudience": "",
"GrantedAudience": "",
"Form": "form_data-0005",
"Subject": "subject-0005",
"Active": false,
"Session": "c2Vzc2lvbi0wMDA1",
"Table": ""
} |
JSON | hydra/persistence/sql/migratest/fixtures/hydra_oauth2_access/sig-0006.json | {
"ID": "sig-0006",
"NID": "00000000-0000-0000-0000-000000000000",
"Request": "req-0006",
"ConsentChallenge": {
"String": "",
"Valid": false
},
"RequestedAt": "0001-01-01T00:00:00Z",
"Client": "",
"Scopes": "scope-0006",
"GrantedScope": "granted_scope-0006",
"RequestedAudience": "",
"GrantedAudience": "",
"Form": "form_data-0006",
"Subject": "subject-0006",
"Active": false,
"Session": "c2Vzc2lvbi0wMDA2",
"Table": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.