perf(oidc): optimize token creation (#7822)

* implement code exchange

* port tokenexchange to v2 tokens

* implement refresh token

* implement client credentials

* implement jwt profile

* implement device token

* cleanup unused code

* fix current unit tests

* add user agent unit test

* unit test domain package

* need refresh token as argument

* test commands create oidc session

* test commands device auth

* fix device auth build error

* implicit for oidc session API

* implement authorize callback handler for legacy implicit mode

* upgrade oidc module to working draft

* add missing auth methods and time

* handle all errors in defer

* do not fail auth request on error

the oauth2 Go client automagically retries on any error. If we fail the auth request on the first error, the next attempt will always fail with the Errors.AuthRequest.NoCode, because the auth request state is already set to failed.
The original error is then already lost and the oauth2 library does not return the original error.

Therefore we should not fail the auth request.

Might be worth discussing and perhaps send a bug report to Oauth2?

* fix code flow tests by explicitly setting code exchanged

* fix unit tests in command package

* return allowed scope from client credential client

* add device auth done reducer

* carry nonce thru session into ID token

* fix token exchange integration tests

* allow project role scope prefix in client credentials client

* gci formatting

* do not return refresh token in client credentials and jwt profile

* check org scope

* solve linting issue on authorize callback error

* end session based on v2 session ID

* use preferred language and user agent ID for v2 access tokens

* pin oidc v3.23.2

* add integration test for jwt profile and client credentials with org scopes

* refresh token v1 to v2

* add user token v2 audit event

* add activity trigger

* cleanup and set panics for unused methods

* use the encrypted code for v1 auth request get by code

* add missing event translation

* fix pipeline errors (hopefully)

* fix another test

* revert pointer usage of preferred language

* solve browser info panic in device auth

* remove duplicate entries in AMRToAuthMethodTypes to prevent future `mfa` claim

* revoke v1 refresh token to prevent reuse

* fix terminate oidc session

* always return a new refresh toke in refresh token grant

---------

Co-authored-by: Livio Spring <livio.a@gmail.com>
This commit is contained in:
Tim Möhlmann
2024-05-16 08:07:56 +03:00
committed by GitHub
parent 6cf9ca9f7e
commit 8e0c8393e9
84 changed files with 3429 additions and 2635 deletions

View File

@@ -34,6 +34,7 @@ type AuthRequest struct {
AvatarKey string
PresignedAvatar string
UserOrgID string
PreferredLanguage *language.Tag
RequestedOrgID string
RequestedOrgName string
RequestedPrimaryDomain string

View File

@@ -11,6 +11,7 @@ type BrowserInfo struct {
UserAgent string
AcceptLanguage string
RemoteIP net.IP
Header net_http.Header
}
func BrowserInfoFromRequest(r *net_http.Request) *BrowserInfo {
@@ -18,5 +19,18 @@ func BrowserInfoFromRequest(r *net_http.Request) *BrowserInfo {
UserAgent: r.Header.Get(http_util.UserAgentHeader),
AcceptLanguage: r.Header.Get(http_util.AcceptLanguage),
RemoteIP: http_util.RemoteIPFromRequest(r),
Header: r.Header,
}
}
func (b *BrowserInfo) ToUserAgent() *UserAgent {
if b == nil {
return nil
}
return &UserAgent{
FingerprintID: &b.UserAgent,
IP: b.RemoteIP,
Description: &b.UserAgent,
Header: b.Header,
}
}

View File

@@ -18,6 +18,7 @@ const (
DeviceAuthStateApproved // approved
DeviceAuthStateDenied // denied
DeviceAuthStateExpired // expired
DeviceAuthStateDone // done
deviceAuthStateCount // invalid
)

View File

@@ -13,12 +13,13 @@ func _() {
_ = x[DeviceAuthStateApproved-2]
_ = x[DeviceAuthStateDenied-3]
_ = x[DeviceAuthStateExpired-4]
_ = x[deviceAuthStateCount-5]
_ = x[DeviceAuthStateDone-5]
_ = x[deviceAuthStateCount-6]
}
const _DeviceAuthState_name = "undefinedinitiatedapproveddeniedexpiredinvalid"
const _DeviceAuthState_name = "undefinedinitiatedapproveddeniedexpireddoneinvalid"
var _DeviceAuthState_index = [...]uint8{0, 9, 18, 26, 32, 39, 46}
var _DeviceAuthState_index = [...]uint8{0, 9, 18, 26, 32, 39, 43, 50}
func (i DeviceAuthState) String() string {
if i >= DeviceAuthState(len(_DeviceAuthState_index)-1) {

View File

@@ -1,5 +1,13 @@
package domain
import (
"errors"
"github.com/zitadel/oidc/v3/pkg/oidc"
"github.com/zitadel/zitadel/internal/zerrors"
)
type OIDCErrorReason int32
const (
@@ -20,4 +28,21 @@ const (
OIDCErrorReasonRequestNotSupported
OIDCErrorReasonRequestURINotSupported
OIDCErrorReasonRegistrationNotSupported
OIDCErrorReasonInvalidGrant
)
func OIDCErrorReasonFromError(err error) OIDCErrorReason {
if errors.Is(err, oidc.ErrInvalidRequest()) {
return OIDCErrorReasonInvalidRequest
}
if errors.Is(err, oidc.ErrInvalidGrant()) {
return OIDCErrorReasonInvalidGrant
}
if zerrors.IsPreconditionFailed(err) {
return OIDCErrorReasonAccessDenied
}
if zerrors.IsInternal(err) {
return OIDCErrorReasonServerError
}
return OIDCErrorReasonUnspecified
}

View File

@@ -0,0 +1,51 @@
package domain
import (
"io"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zitadel/oidc/v3/pkg/oidc"
"github.com/zitadel/zitadel/internal/zerrors"
)
func TestOIDCErrorReasonFromError(t *testing.T) {
tests := []struct {
name string
err error
want OIDCErrorReason
}{
{
name: "invalid request",
err: oidc.ErrInvalidRequest().WithDescription("foo"),
want: OIDCErrorReasonInvalidRequest,
},
{
name: "invalid grant",
err: oidc.ErrInvalidGrant().WithDescription("foo"),
want: OIDCErrorReasonInvalidGrant,
},
{
name: "precondition failed",
err: zerrors.ThrowPreconditionFailed(nil, "123", "bar"),
want: OIDCErrorReasonAccessDenied,
},
{
name: "internal",
err: zerrors.ThrowInternal(nil, "123", "bar"),
want: OIDCErrorReasonServerError,
},
{
name: "unspecified",
err: io.ErrClosedPipe,
want: OIDCErrorReasonUnspecified,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := OIDCErrorReasonFromError(tt.err)
assert.Equal(t, tt.want, got)
})
}
}

View File

@@ -3,27 +3,10 @@ package domain
import (
"context"
"strings"
"time"
"github.com/zitadel/zitadel/internal/api/authz"
es_models "github.com/zitadel/zitadel/internal/eventstore/v1/models"
)
type Token struct {
es_models.ObjectRoot
TokenID string
ApplicationID string
UserAgentID string
RefreshTokenID string
Audience []string
Expiration time.Time
Scopes []string
PreferredLanguage string
Reason TokenReason
Actor *TokenActor
}
func AddAudScopeToAudience(ctx context.Context, audience, scopes []string) []string {
for _, scope := range scopes {
if !(strings.HasPrefix(scope, ProjectIDScope) && strings.HasSuffix(scope, AudSuffix)) {

View File

@@ -15,3 +15,10 @@ type UserAgent struct {
func (ua UserAgent) IsEmpty() bool {
return ua.FingerprintID == nil && len(ua.IP) == 0 && ua.Description == nil && ua.Header == nil
}
func (ua *UserAgent) GetFingerprintID() string {
if ua == nil || ua.FingerprintID == nil {
return ""
}
return *ua.FingerprintID
}

View File

@@ -0,0 +1,42 @@
package domain
import (
"testing"
"github.com/muhlemmer/gu"
"github.com/stretchr/testify/assert"
)
func TestUserAgent_GetFingerprintID(t *testing.T) {
tests := []struct {
name string
fields *UserAgent
want string
}{
{
name: "nil useragent",
fields: nil,
want: "",
},
{
name: "nil fingerprintID",
fields: &UserAgent{
FingerprintID: nil,
},
want: "",
},
{
name: "value",
fields: &UserAgent{
FingerprintID: gu.Ptr("fp"),
},
want: "fp",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := tt.fields.GetFingerprintID()
assert.Equal(t, tt.want, got)
})
}
}