Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(transactions): add transaction api #24

Merged
merged 5 commits into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 66 additions & 2 deletions server/api/dto/request/requests.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
package request

type CredentialRequest interface {
import (
"encoding/json"
"github.com/gofrs/uuid"
"github.com/teamhanko/passkey-server/persistence/models"
"strings"
"time"
)

type CredentialRequests interface {
ListCredentialsDto | DeleteCredentialsDto | UpdateCredentialsDto
}

Expand All @@ -21,9 +29,65 @@ type UpdateCredentialsDto struct {
Name string `json:"name" validate:"required"`
}

type WebauthnRequests interface {
InitRegistrationDto | InitTransactionDto
}

type InitRegistrationDto struct {
UserId string `json:"user_id" validate:"required"`
Username string `json:"username" validate:"required,max=128"`
DisplayName *string `json:"display_name,max=128"`
DisplayName *string `json:"display_name" validate:"omitempty,max=128"`
Icon *string `json:"icon"`
}

func (initRegistration *InitRegistrationDto) ToModel() *models.WebauthnUser {
icon := ""
if initRegistration.Icon != nil {
icon = *initRegistration.Icon
}

displayName := initRegistration.Username
if initRegistration.DisplayName != nil && len(strings.TrimSpace(*initRegistration.DisplayName)) > 0 {
displayName = *initRegistration.DisplayName
}

webauthnId, _ := uuid.NewV4()

now := time.Now()

return &models.WebauthnUser{
ID: webauthnId,
UserID: initRegistration.UserId,
Name: initRegistration.Username,
Icon: icon,
DisplayName: displayName,
CreatedAt: now,
UpdatedAt: now,
}
}

type InitTransactionDto struct {
UserId string `json:"user_id" validate:"required"`
TransactionId string `json:"transaction_id" validate:"required,max=128"`
TransactionData interface{} `json:"transaction_data" validate:"required"`
}

func (initTransaction *InitTransactionDto) ToModel() (*models.Transaction, error) {
transactionUuid, _ := uuid.NewV4()

byteArray, err := json.Marshal(initTransaction.TransactionData)
if err != nil {
return nil, err
}

now := time.Now()

return &models.Transaction{
ID: transactionUuid,
Identifier: initTransaction.TransactionId,
Data: string(byteArray),

CreatedAt: now,
UpdatedAt: now,
}, nil
}
4 changes: 2 additions & 2 deletions server/api/handler/credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ func (credHandler *credentialsHandler) Update(ctx echo.Context) error {
ctx.Logger().Error(err)
return err
}
err := h.AuditLog.CreateWithConnection(tx, ctx, h.Tenant, models.AuditLogWebAuthnCredentialUpdated, &credential.UserId, nil)
err := h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnCredentialUpdated, &credential.UserId, nil, nil)
if err != nil {
ctx.Logger().Error(err)
return err
Expand Down Expand Up @@ -132,7 +132,7 @@ func (credHandler *credentialsHandler) Delete(ctx echo.Context) error {
return err
}

err = h.AuditLog.CreateWithConnection(tx, ctx, h.Tenant, models.AuditLogWebAuthnCredentialDeleted, nil, nil)
err = h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnCredentialDeleted, nil, nil, nil)
if err != nil {
ctx.Logger().Error(err)
return err
Expand Down
115 changes: 46 additions & 69 deletions server/api/handler/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,48 +39,50 @@ func (lh *loginHandler) Init(ctx echo.Context) error {
return err
}

options, sessionData, err := h.Webauthn.BeginDiscoverableLogin(
webauthn.WithUserVerification(h.Config.WebauthnConfig.UserVerification),
)
if err != nil {
auditErr := h.AuditLog.Create(ctx, h.Tenant, models.AuditLogWebAuthnAuthenticationInitFailed, nil, err)
if auditErr != nil {
ctx.Logger().Error(auditErr)
return fmt.Errorf(auditlog.CreationFailureFormat, auditErr)
return lh.persister.GetConnection().Transaction(func(tx *pop.Connection) error {
options, sessionData, err := h.Webauthn.BeginDiscoverableLogin(
webauthn.WithUserVerification(h.Config.WebauthnConfig.UserVerification),
)
if err != nil {
auditErr := h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnAuthenticationInitFailed, nil, nil, err)
if auditErr != nil {
ctx.Logger().Error(auditErr)
return fmt.Errorf(auditlog.CreationFailureFormat, auditErr)
}

ctx.Logger().Error(err)
return echo.NewHTTPError(
http.StatusBadRequest,
fmt.Errorf("failed to create webauthn assertion options for discoverable login: %w", err),
)
}

ctx.Logger().Error(err)
return echo.NewHTTPError(
http.StatusBadRequest,
fmt.Errorf("failed to create webauthn assertion options for discoverable login: %w", err),
)
}
err = lh.persister.GetWebauthnSessionDataPersister(tx).Create(*intern.WebauthnSessionDataToModel(sessionData, h.Tenant.ID, models.WebauthnOperationAuthentication))
if err != nil {
auditErr := h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnAuthenticationInitFailed, nil, nil, err)
if auditErr != nil {
ctx.Logger().Error(auditErr)
return fmt.Errorf(auditlog.CreationFailureFormat, auditErr)
}

err = lh.persister.GetWebauthnSessionDataPersister(nil).Create(*intern.WebauthnSessionDataToModel(sessionData, h.Tenant.ID, models.WebauthnOperationAuthentication))
if err != nil {
auditErr := h.AuditLog.Create(ctx, h.Tenant, models.AuditLogWebAuthnAuthenticationInitFailed, nil, err)
ctx.Logger().Error(err)
return fmt.Errorf("failed to store webauthn assertion session data: %w", err)
}

// Remove all transports, because of a bug in android and windows where the internal authenticator gets triggered,
// when the transports array contains the type 'internal' although the credential is not available on the device.
for i := range options.Response.AllowedCredentials {
options.Response.AllowedCredentials[i].Transport = nil
}

auditErr := h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnAuthenticationInitSucceeded, nil, nil, nil)
if auditErr != nil {
ctx.Logger().Error(auditErr)
return fmt.Errorf(auditlog.CreationFailureFormat, auditErr)
}

ctx.Logger().Error(err)
return fmt.Errorf("failed to store webauthn assertion session data: %w", err)
}

// Remove all transports, because of a bug in android and windows where the internal authenticator gets triggered,
// when the transports array contains the type 'internal' although the credential is not available on the device.
for i := range options.Response.AllowedCredentials {
options.Response.AllowedCredentials[i].Transport = nil
}

auditErr := h.AuditLog.Create(ctx, h.Tenant, models.AuditLogWebAuthnAuthenticationInitSucceeded, nil, nil)
if auditErr != nil {
ctx.Logger().Error(auditErr)
return fmt.Errorf(auditlog.CreationFailureFormat, auditErr)
}

return ctx.JSON(http.StatusOK, options)
return ctx.JSON(http.StatusOK, options)
})
}

func (lh *loginHandler) Finish(ctx echo.Context) error {
Expand All @@ -101,9 +103,13 @@ func (lh *loginHandler) Finish(ctx echo.Context) error {
webauthnUserPersister := lh.persister.GetWebauthnUserPersister(tx)
credentialPersister := lh.persister.GetWebauthnCredentialPersister(tx)

// backward compatibility
userHandle := lh.convertUserHandle(parsedRequest.Response.UserHandle)
parsedRequest.Response.UserHandle = []byte(userHandle)

sessionData, err := lh.getSessionDataByChallenge(parsedRequest.Response.CollectedClientData.Challenge, sessionDataPersister, h.Tenant.ID)
if err != nil {
auditErr := h.AuditLog.Create(ctx, h.Tenant, models.AuditLogWebAuthnAuthenticationFinalFailed, nil, err)
auditErr := h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnAuthenticationFinalFailed, nil, nil, err)
if auditErr != nil {
ctx.Logger().Error(auditErr)
return fmt.Errorf(auditlog.CreationFailureFormat, auditErr)
Expand All @@ -114,9 +120,9 @@ func (lh *loginHandler) Finish(ctx echo.Context) error {
}
sessionDataModel := intern.WebauthnSessionDataFromModel(sessionData)

webauthnUser, err := lh.getWebauthnUserByUserHandle(parsedRequest.Response.UserHandle, h.Tenant.ID, webauthnUserPersister)
webauthnUser, err := lh.getWebauthnUserByUserHandle(userHandle, h.Tenant.ID, webauthnUserPersister)
if err != nil {
auditErr := h.AuditLog.Create(ctx, h.Tenant, models.AuditLogWebAuthnAuthenticationFinalFailed, &webauthnUser.UserId, err)
auditErr := h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnAuthenticationFinalFailed, &webauthnUser.UserId, nil, err)
if auditErr != nil {
ctx.Logger().Error(auditErr)
return fmt.Errorf(auditlog.CreationFailureFormat, auditErr)
Expand All @@ -126,16 +132,12 @@ func (lh *loginHandler) Finish(ctx echo.Context) error {
return echo.NewHTTPError(http.StatusUnauthorized, "failed to get user handle").SetInternal(err)
}

// backward compatibility
userId := lh.convertUserHandle(parsedRequest.Response.UserHandle)
parsedRequest.Response.UserHandle = []byte(userId)

credential, err := h.Webauthn.ValidateDiscoverableLogin(func(rawID, userHandle []byte) (user webauthn.User, err error) {
return webauthnUser, nil
}, *sessionDataModel, parsedRequest)

if err != nil {
auditErr := h.AuditLog.Create(ctx, h.Tenant, models.AuditLogWebAuthnAuthenticationFinalFailed, &webauthnUser.UserId, err)
auditErr := h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnAuthenticationFinalFailed, &webauthnUser.UserId, nil, err)
if auditErr != nil {
ctx.Logger().Error(auditErr)
return fmt.Errorf(auditlog.CreationFailureFormat, auditErr)
Expand All @@ -155,7 +157,7 @@ func (lh *loginHandler) Finish(ctx echo.Context) error {
dbCred.LastUsedAt = &now
err = credentialPersister.Update(dbCred)
if err != nil {
auditErr := h.AuditLog.Create(ctx, h.Tenant, models.AuditLogWebAuthnAuthenticationFinalFailed, &webauthnUser.UserId, err)
auditErr := h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnAuthenticationFinalFailed, &webauthnUser.UserId, nil, err)
if auditErr != nil {
ctx.Logger().Error(auditErr)
return fmt.Errorf(auditlog.CreationFailureFormat, auditErr)
Expand All @@ -179,7 +181,7 @@ func (lh *loginHandler) Finish(ctx echo.Context) error {
return fmt.Errorf("failed to generate jwt: %w", err)
}

auditErr := h.AuditLog.Create(ctx, h.Tenant, models.AuditLogWebAuthnAuthenticationFinalSucceeded, &webauthnUser.UserId, nil)
auditErr := h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnAuthenticationFinalSucceeded, &webauthnUser.UserId, nil, nil)
if auditErr != nil {
ctx.Logger().Error(auditErr)
return fmt.Errorf(auditlog.CreationFailureFormat, auditErr)
Expand All @@ -205,28 +207,3 @@ func (lh *loginHandler) getSessionDataByChallenge(challenge string, persister pe

return sessionData, nil
}

func (lh *loginHandler) getWebauthnUserByUserHandle(userHandle []byte, tenantId uuid.UUID, persister persisters.WebauthnUserPersister) (*intern.WebauthnUser, error) {
userId := lh.convertUserHandle(userHandle)

user, err := persister.GetByUserId(userId, tenantId)
if err != nil {
return nil, fmt.Errorf("failed to get user: %w", err)
}

if user == nil {
return nil, fmt.Errorf("user not found")
}

return intern.NewWebauthnUser(*user), nil
}

func (lh *loginHandler) convertUserHandle(userHandle []byte) string {
userId := string(userHandle)
userUuid, err := uuid.FromBytes(userHandle)
if err == nil {
userId = userUuid.String()
}

return userId
}
24 changes: 10 additions & 14 deletions server/api/handler/registration.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,7 @@ func (r *registrationHandler) Init(ctx echo.Context) error {
return err
}

webauthnUser, err := models.FromRegistrationDto(dto)
if err != nil {
ctx.Logger().Error(err)
return fmt.Errorf("unable to parse user object: %w", err)
}
webauthnUser := dto.ToModel()

h, err := helper.GetHandlerContext(ctx)
if err != nil {
Expand All @@ -59,7 +55,7 @@ func (r *registrationHandler) Init(ctx echo.Context) error {
webauthnUser.Tenant = h.Tenant
internalUserDto, userModel, err := r.GetWebauthnUser(webauthnUser.UserID, webauthnUser.Tenant.ID, webauthnUserPersister)
if err != nil {
auditErr := h.AuditLog.CreateWithConnection(tx, ctx, h.Tenant, models.AuditLogWebAuthnRegistrationInitFailed, &webauthnUser.UserID, err)
auditErr := h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnRegistrationInitFailed, &webauthnUser.UserID, nil, err)
if auditErr != nil {
ctx.Logger().Error(auditErr)
return fmt.Errorf(auditlog.CreationFailureFormat, auditErr)
Expand All @@ -72,7 +68,7 @@ func (r *registrationHandler) Init(ctx echo.Context) error {
if internalUserDto == nil {
err = webauthnUserPersister.Create(webauthnUser)
if err != nil {
auditErr := h.AuditLog.CreateWithConnection(tx, ctx, h.Tenant, models.AuditLogWebAuthnRegistrationInitFailed, &webauthnUser.UserID, err)
auditErr := h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnRegistrationInitFailed, &webauthnUser.UserID, nil, err)
if auditErr != nil {
ctx.Logger().Error(auditErr)
return fmt.Errorf(auditlog.CreationFailureFormat, auditErr)
Expand All @@ -86,7 +82,7 @@ func (r *registrationHandler) Init(ctx echo.Context) error {
} else {
internalUserDto, err = r.updateWebauthnUser(userModel, webauthnUser, webauthnUserPersister)
if err != nil {
auditErr := h.AuditLog.CreateWithConnection(tx, ctx, h.Tenant, models.AuditLogWebAuthnRegistrationInitFailed, &webauthnUser.UserID, err)
auditErr := h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnRegistrationInitFailed, &webauthnUser.UserID, nil, err)
if auditErr != nil {
ctx.Logger().Error(auditErr)
return fmt.Errorf(auditlog.CreationFailureFormat, auditErr)
Expand All @@ -109,7 +105,7 @@ func (r *registrationHandler) Init(ctx echo.Context) error {
// don't set the excludeCredentials list, so an already registered device can be re-registered
)
if err != nil {
auditErr := h.AuditLog.CreateWithConnection(tx, ctx, h.Tenant, models.AuditLogWebAuthnRegistrationInitFailed, &webauthnUser.UserID, err)
auditErr := h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnRegistrationInitFailed, &webauthnUser.UserID, nil, err)
if auditErr != nil {
ctx.Logger().Error(auditErr)
return fmt.Errorf(auditlog.CreationFailureFormat, auditErr)
Expand All @@ -121,7 +117,7 @@ func (r *registrationHandler) Init(ctx echo.Context) error {

err = webauthnSessionPersister.Create(*intern.WebauthnSessionDataToModel(sessionData, h.Tenant.ID, models.WebauthnOperationRegistration))
if err != nil {
auditErr := h.AuditLog.CreateWithConnection(tx, ctx, h.Tenant, models.AuditLogWebAuthnRegistrationInitFailed, &webauthnUser.UserID, err)
auditErr := h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnRegistrationInitFailed, &webauthnUser.UserID, nil, err)
if auditErr != nil {
ctx.Logger().Error(auditErr)
return fmt.Errorf(auditlog.CreationFailureFormat, auditErr)
Expand All @@ -131,7 +127,7 @@ func (r *registrationHandler) Init(ctx echo.Context) error {
return fmt.Errorf("failed to create session data: %w", err)
}

err = h.AuditLog.CreateWithConnection(tx, ctx, h.Tenant, models.AuditLogWebAuthnRegistrationInitSucceeded, &webauthnUser.UserID, nil)
err = h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnRegistrationInitSucceeded, &webauthnUser.UserID, nil, nil)
if err != nil {
ctx.Logger().Error(err)
return fmt.Errorf(auditlog.CreationFailureFormat, err)
Expand Down Expand Up @@ -192,7 +188,7 @@ func (r *registrationHandler) Finish(ctx echo.Context) error {
errorStatus = http.StatusUnprocessableEntity
}

auditErr := h.AuditLog.CreateWithConnection(tx, ctx, h.Tenant, models.AuditLogWebAuthnRegistrationFinalFailed, &webauthnUser.UserId, err)
auditErr := h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnRegistrationFinalFailed, &webauthnUser.UserId, nil, err)
if auditErr != nil {
ctx.Logger().Error(auditErr)
return fmt.Errorf(auditlog.CreationFailureFormat, auditErr)
Expand All @@ -206,7 +202,7 @@ func (r *registrationHandler) Finish(ctx echo.Context) error {
model := intern.WebauthnCredentialToModel(credential, sessionData.UserId, userModel.ID, flags.HasBackupEligible(), flags.HasBackupState())
err = r.persister.GetWebauthnCredentialPersister(tx).Create(model)
if err != nil {
auditErr := h.AuditLog.CreateWithConnection(tx, ctx, h.Tenant, models.AuditLogWebAuthnRegistrationFinalFailed, &webauthnUser.UserId, err)
auditErr := h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnRegistrationFinalFailed, &webauthnUser.UserId, nil, err)
if auditErr != nil {
ctx.Logger().Error(auditErr)
return fmt.Errorf(auditlog.CreationFailureFormat, auditErr)
Expand All @@ -228,7 +224,7 @@ func (r *registrationHandler) Finish(ctx echo.Context) error {
return fmt.Errorf("failed to generate jwt: %w", err)
}

err = h.AuditLog.CreateWithConnection(tx, ctx, h.Tenant, models.AuditLogWebAuthnRegistrationFinalSucceeded, &webauthnUser.UserId, nil)
err = h.AuditLog.CreateWithConnection(tx, models.AuditLogWebAuthnRegistrationFinalSucceeded, &webauthnUser.UserId, nil, nil)
if err != nil {
ctx.Logger().Error(err)
return fmt.Errorf(auditlog.CreationFailureFormat, err)
Expand Down
Loading