mirror of
https://github.com/zitadel/zitadel.git
synced 2024-12-14 20:08:02 +00:00
8e0c8393e9
* 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>
180 lines
5.6 KiB
Go
180 lines
5.6 KiB
Go
package command
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"golang.org/x/text/language"
|
|
|
|
"github.com/zitadel/zitadel/internal/api/authz"
|
|
"github.com/zitadel/zitadel/internal/domain"
|
|
"github.com/zitadel/zitadel/internal/eventstore"
|
|
"github.com/zitadel/zitadel/internal/repository/deviceauth"
|
|
"github.com/zitadel/zitadel/internal/telemetry/tracing"
|
|
"github.com/zitadel/zitadel/internal/zerrors"
|
|
)
|
|
|
|
func (c *Commands) AddDeviceAuth(ctx context.Context, clientID, deviceCode, userCode string, expires time.Time, scopes, audience []string, needRefreshToken bool) (*domain.ObjectDetails, error) {
|
|
aggr := deviceauth.NewAggregate(deviceCode, authz.GetInstance(ctx).InstanceID())
|
|
model := NewDeviceAuthWriteModel(deviceCode, aggr.ResourceOwner)
|
|
|
|
pushedEvents, err := c.eventstore.Push(ctx, deviceauth.NewAddedEvent(
|
|
ctx,
|
|
aggr,
|
|
clientID,
|
|
deviceCode,
|
|
userCode,
|
|
expires,
|
|
scopes,
|
|
audience,
|
|
needRefreshToken,
|
|
))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
err = AppendAndReduce(model, pushedEvents...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return writeModelToObjectDetails(&model.WriteModel), nil
|
|
}
|
|
|
|
func (c *Commands) ApproveDeviceAuth(
|
|
ctx context.Context,
|
|
deviceCode,
|
|
userID,
|
|
userOrgID string,
|
|
authMethods []domain.UserAuthMethodType,
|
|
authTime time.Time,
|
|
preferredLanguage *language.Tag,
|
|
userAgent *domain.UserAgent,
|
|
) (*domain.ObjectDetails, error) {
|
|
model, err := c.getDeviceAuthWriteModelByDeviceCode(ctx, deviceCode)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !model.State.Exists() {
|
|
return nil, zerrors.ThrowNotFound(nil, "COMMAND-Hief9", "Errors.DeviceAuth.NotFound")
|
|
}
|
|
pushedEvents, err := c.eventstore.Push(ctx, deviceauth.NewApprovedEvent(ctx, model.aggregate, userID, userOrgID, authMethods, authTime, preferredLanguage, userAgent))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
err = AppendAndReduce(model, pushedEvents...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return writeModelToObjectDetails(&model.WriteModel), nil
|
|
}
|
|
|
|
func (c *Commands) CancelDeviceAuth(ctx context.Context, id string, reason domain.DeviceAuthCanceled) (*domain.ObjectDetails, error) {
|
|
model, err := c.getDeviceAuthWriteModelByDeviceCode(ctx, id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !model.State.Exists() {
|
|
return nil, zerrors.ThrowNotFound(nil, "COMMAND-gee5A", "Errors.DeviceAuth.NotFound")
|
|
}
|
|
pushedEvents, err := c.eventstore.Push(ctx, deviceauth.NewCanceledEvent(ctx, model.aggregate, reason))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
err = AppendAndReduce(model, pushedEvents...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return writeModelToObjectDetails(&model.WriteModel), nil
|
|
}
|
|
|
|
func (c *Commands) getDeviceAuthWriteModelByDeviceCode(ctx context.Context, deviceCode string) (*DeviceAuthWriteModel, error) {
|
|
model := &DeviceAuthWriteModel{
|
|
WriteModel: eventstore.WriteModel{AggregateID: deviceCode},
|
|
}
|
|
err := c.eventstore.FilterToQueryReducer(ctx, model)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
model.aggregate = deviceauth.NewAggregate(model.AggregateID, model.InstanceID)
|
|
return model, nil
|
|
}
|
|
|
|
type DeviceAuthStateError domain.DeviceAuthState
|
|
|
|
func (e DeviceAuthStateError) Error() string {
|
|
return fmt.Sprintf("device auth state not approved: %s", domain.DeviceAuthState(e).String())
|
|
}
|
|
|
|
// CreateOIDCSessionFromDeviceAuth creates a new OIDC session if the device authorization
|
|
// flow is completed (user logged in).
|
|
// A [DeviceAuthStateError] is returned if the device authorization was not approved,
|
|
// containing a [domain.DeviceAuthState] which can be used to inform the client about the state.
|
|
//
|
|
// As devices can poll at various intervals, an explicit state takes precedence over expiry.
|
|
// This is to prevent cases where users might approve or deny the authorization on time, but the next poll
|
|
// happens after expiry.
|
|
func (c *Commands) CreateOIDCSessionFromDeviceAuth(ctx context.Context, deviceCode string) (_ *OIDCSession, err error) {
|
|
ctx, span := tracing.NewSpan(ctx)
|
|
defer func() { span.EndWithError(err) }()
|
|
|
|
deviceAuthModel, err := c.getDeviceAuthWriteModelByDeviceCode(ctx, deviceCode)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
switch deviceAuthModel.State {
|
|
case domain.DeviceAuthStateApproved:
|
|
break
|
|
case domain.DeviceAuthStateUndefined:
|
|
return nil, zerrors.ThrowNotFound(nil, "COMMAND-ua1Vo", "Errors.DeviceAuth.NotFound")
|
|
|
|
case domain.DeviceAuthStateInitiated:
|
|
if deviceAuthModel.Expires.Before(time.Now()) {
|
|
c.asyncPush(ctx, deviceauth.NewCanceledEvent(ctx, deviceAuthModel.aggregate, domain.DeviceAuthCanceledExpired))
|
|
return nil, DeviceAuthStateError(domain.DeviceAuthStateExpired)
|
|
}
|
|
fallthrough
|
|
case domain.DeviceAuthStateDenied, domain.DeviceAuthStateExpired, domain.DeviceAuthStateDone:
|
|
fallthrough
|
|
default:
|
|
return nil, DeviceAuthStateError(deviceAuthModel.State)
|
|
}
|
|
|
|
cmd, err := c.newOIDCSessionAddEvents(ctx, deviceAuthModel.UserOrgID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
cmd.AddSession(ctx,
|
|
deviceAuthModel.UserID,
|
|
deviceAuthModel.UserOrgID,
|
|
"",
|
|
deviceAuthModel.ClientID,
|
|
deviceAuthModel.Audience,
|
|
deviceAuthModel.Scopes,
|
|
deviceAuthModel.UserAuthMethods,
|
|
deviceAuthModel.AuthTime,
|
|
"",
|
|
deviceAuthModel.PreferredLanguage,
|
|
deviceAuthModel.UserAgent,
|
|
)
|
|
if err = cmd.AddAccessToken(ctx, deviceAuthModel.Scopes, deviceAuthModel.UserID, deviceAuthModel.UserOrgID, domain.TokenReasonAuthRequest, nil); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if deviceAuthModel.NeedRefreshToken {
|
|
if err = cmd.AddRefreshToken(ctx, deviceAuthModel.UserID); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
cmd.DeviceAuthRequestDone(ctx, deviceAuthModel.aggregate)
|
|
return cmd.PushEvents(ctx)
|
|
}
|
|
|
|
func (cmd *OIDCSessionEvents) DeviceAuthRequestDone(ctx context.Context, deviceAuthAggregate *eventstore.Aggregate) {
|
|
cmd.events = append(cmd.events, deviceauth.NewDoneEvent(ctx, deviceAuthAggregate))
|
|
}
|