Skip to content

Commit 6ccc7ba

Browse files
AmanGIT07claude
andauthored
fix(authenticate): read otp attempt counter from json-decoded metadata (#1846)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
1 parent ad5e9a5 commit 6ccc7ba

2 files changed

Lines changed: 104 additions & 7 deletions

File tree

‎core/authenticate/service.go‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,20 @@ func (s Service) FinishFlow(ctx context.Context, request RegistrationFinishReque
363363
return nil, ErrUnsupportedMethod
364364
}
365365

366+
// otpAttempts reads the wrong-code attempt counter from flow metadata.
367+
// The counter is written as an int, but flow metadata is stored as JSON
368+
// in the database, and JSON unmarshaling returns numbers as float64.
369+
func otpAttempts(md metadata.Metadata) int {
370+
switch attempts := md[otpAttemptKey].(type) {
371+
case int:
372+
return attempts
373+
case float64:
374+
return int(attempts)
375+
default:
376+
return 0
377+
}
378+
}
379+
366380
// applyMailOTP actions when user submitted otp from the email
367381
// user can be considered as verified if code is valid
368382
// create a new user if required
@@ -384,12 +398,9 @@ func (s Service) applyMailOTP(ctx context.Context, request RegistrationFinishReq
384398

385399
if bcrypt.CompareHashAndPassword([]byte(flow.Nonce), []byte(request.Code)) != nil {
386400
// avoid brute forcing otp
387-
attemptInt := 0
388-
if attempts, ok := flow.Metadata[otpAttemptKey]; ok {
389-
attemptInt, _ = attempts.(int)
390-
}
401+
attemptInt := otpAttempts(flow.Metadata) + 1
391402
if attemptInt < maxOTPAttempt {
392-
flow.Metadata[otpAttemptKey] = attemptInt + 1
403+
flow.Metadata[otpAttemptKey] = attemptInt
393404
if err = s.flowRepo.Set(ctx, flow); err != nil {
394405
return nil, fmt.Errorf("failed to process flow code missmatch")
395406
}

‎core/authenticate/service_test.go‎

Lines changed: 88 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package authenticate_test
33
import (
44
"context"
55
"encoding/base64"
6+
"encoding/json"
67
"errors"
78
"io"
89
"log/slog"
@@ -575,7 +576,7 @@ func TestService_FinishFlow(t *testing.T) {
575576
},
576577
},
577578
{
578-
name: "destroy the flow if the code is wrong past the attempt cap",
579+
name: "destroy the flow if the wrong code reaches the attempt cap",
579580
args: args{
580581
ctx: context.Background(),
581582
request: authenticate.RegistrationFinishRequest{
@@ -590,7 +591,7 @@ func TestService_FinishFlow(t *testing.T) {
590591
mockFlowRepo, _, _, _, _ := createMocks(t)
591592
ctx := context.Background()
592593
mockFlowRepo.EXPECT().Get(ctx, flowID).
593-
Return(mailOTPFlow(flowID, timeNow, string(otpHash), pkgMetadata.Metadata{"callback_url": "", "attempt": 3}), nil)
594+
Return(mailOTPFlow(flowID, timeNow, string(otpHash), pkgMetadata.Metadata{"callback_url": "", "attempt": 2}), nil)
594595
mockFlowRepo.EXPECT().Delete(ctx, flowID).Return(nil)
595596
srv := authenticate.NewService(nil, authenticate.Config{}, mockFlowRepo, nil,
596597
nil, nil, nil, nil, nil, nil)
@@ -657,6 +658,91 @@ func TestService_FinishFlow_WrongThenRightOTP(t *testing.T) {
657658
assert.Equal(t, sampleUser, got.User)
658659
}
659660

661+
// jsonFlowRepository keeps flow metadata as JSON bytes, the same way the
662+
// Postgres repository stores it. Numbers in metadata come back from Get as
663+
// float64, matching a real database round trip.
664+
type jsonFlowRepository struct {
665+
flows map[uuid.UUID]jsonStoredFlow
666+
}
667+
668+
type jsonStoredFlow struct {
669+
flow authenticate.Flow
670+
rawMetadata []byte
671+
}
672+
673+
func (r *jsonFlowRepository) Set(_ context.Context, flow *authenticate.Flow) error {
674+
raw, err := json.Marshal(flow.Metadata)
675+
if err != nil {
676+
return err
677+
}
678+
r.flows[flow.ID] = jsonStoredFlow{flow: *flow, rawMetadata: raw}
679+
return nil
680+
}
681+
682+
func (r *jsonFlowRepository) Get(_ context.Context, id uuid.UUID) (*authenticate.Flow, error) {
683+
stored, ok := r.flows[id]
684+
if !ok {
685+
return nil, authenticate.ErrFlowInvalid
686+
}
687+
flow := stored.flow
688+
var md pkgMetadata.Metadata
689+
if err := json.Unmarshal(stored.rawMetadata, &md); err != nil {
690+
return nil, err
691+
}
692+
flow.Metadata = md
693+
return &flow, nil
694+
}
695+
696+
func (r *jsonFlowRepository) Delete(_ context.Context, id uuid.UUID) error {
697+
delete(r.flows, id)
698+
return nil
699+
}
700+
701+
func (r *jsonFlowRepository) DeleteExpiredFlows(_ context.Context) error {
702+
return nil
703+
}
704+
705+
func TestService_FinishFlow_OTPAttemptCapAfterJSONRoundTrip(t *testing.T) {
706+
flowID := uuid.New()
707+
timeNow := time.Now()
708+
otpHash, err := bcrypt.GenerateFromPassword([]byte("111111"), bcrypt.MinCost)
709+
require.NoError(t, err)
710+
711+
ctx := context.Background()
712+
flowRepo := &jsonFlowRepository{flows: map[uuid.UUID]jsonStoredFlow{}}
713+
require.NoError(t, flowRepo.Set(ctx, mailOTPFlow(flowID, timeNow, string(otpHash), pkgMetadata.Metadata{"callback_url": ""})))
714+
715+
srv := authenticate.NewService(nil, authenticate.Config{}, flowRepo, nil,
716+
nil, nil, nil, nil, nil, nil)
717+
srv.Now = func() time.Time {
718+
return timeNow
719+
}
720+
721+
wrongCode := authenticate.RegistrationFinishRequest{
722+
Method: authenticate.MailOTPAuthMethod.String(),
723+
State: flowID.String(),
724+
Code: "222222",
725+
}
726+
727+
for attempt := 1; attempt <= 2; attempt++ {
728+
got, err := srv.FinishFlow(ctx, wrongCode)
729+
assert.ErrorIs(t, err, authenticate.ErrInvalidMailOTP)
730+
assert.Nil(t, got)
731+
732+
flow, err := flowRepo.Get(ctx, flowID)
733+
require.NoError(t, err)
734+
assert.Equal(t, float64(attempt), flow.Metadata["attempt"])
735+
}
736+
737+
// the third wrong code reaches the cap and destroys the flow
738+
got, err := srv.FinishFlow(ctx, wrongCode)
739+
assert.ErrorIs(t, err, authenticate.ErrInvalidMailOTP)
740+
assert.Nil(t, got)
741+
742+
_, err = flowRepo.Get(ctx, flowID)
743+
assert.ErrorIs(t, err, authenticate.ErrFlowInvalid)
744+
}
745+
660746
func TestService_GetPrincipal_JWTGrantSkipsNonGrantToken(t *testing.T) {
661747
userID := uuid.New()
662748
patValue := "fpt_opaque-not-a-jwt"

0 commit comments

Comments
 (0)