|
| 1 | +package api |
| 2 | + |
| 3 | +// Tests for how submitRegistration maps store errors (issue #137): the 409 |
| 4 | +// "already registered" answer comes only from the typed duplicate sentinel, |
| 5 | +// never from the word "duplicate" in an error message. |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "errors" |
| 10 | + "fmt" |
| 11 | + "testing" |
| 12 | + |
| 13 | + "github.com/aws/aws-lambda-go/events" |
| 14 | + "github.com/jackc/pgx/v5/pgconn" |
| 15 | + "github.com/stretchr/testify/assert" |
| 16 | + "github.com/stretchr/testify/mock" |
| 17 | + "github.com/stretchr/testify/require" |
| 18 | + |
| 19 | + "github.com/LeanerCloud/cloud-commitments-platform/internal/config" |
| 20 | + "github.com/LeanerCloud/cloud-commitments-platform/internal/email" |
| 21 | +) |
| 22 | + |
| 23 | +// countingRegistrationNotifier counts admin "registration received" emails. |
| 24 | +type countingRegistrationNotifier struct { |
| 25 | + stubEmailNotifier |
| 26 | + received int |
| 27 | +} |
| 28 | + |
| 29 | +func (n *countingRegistrationNotifier) SendRegistrationReceivedNotification(_ context.Context, _ email.RegistrationNotificationData) error { |
| 30 | + n.received++ |
| 31 | + return nil |
| 32 | +} |
| 33 | + |
| 34 | +const submitRegistrationBody = `{"provider":"aws","external_id":"123456789012",` + |
| 35 | + `"account_name":"Prod","contact_email":"owner@example.com"}` |
| 36 | + |
| 37 | +func submitRegistrationRequest() *events.LambdaFunctionURLRequest { |
| 38 | + return &events.LambdaFunctionURLRequest{Body: submitRegistrationBody} |
| 39 | +} |
| 40 | + |
| 41 | +func TestSubmitRegistration_DuplicatePending_Returns409WithoutEmail(t *testing.T) { |
| 42 | + ctx := context.Background() |
| 43 | + store := new(MockConfigStore) |
| 44 | + store.On("CreateAccountRegistration", ctx, mock.Anything). |
| 45 | + Return(fmt.Errorf("%w: %w", config.ErrDuplicatePendingRegistration, |
| 46 | + &pgconn.PgError{Code: "23505", ConstraintName: "idx_account_registrations_pending_unique"})).Once() |
| 47 | + notifier := &countingRegistrationNotifier{} |
| 48 | + h := &Handler{config: store, emailNotifier: notifier} |
| 49 | + |
| 50 | + _, err := h.submitRegistration(ctx, submitRegistrationRequest()) |
| 51 | + |
| 52 | + ce, ok := IsClientError(err) |
| 53 | + require.True(t, ok, "duplicate must be a client error, got %v", err) |
| 54 | + assert.Equal(t, 409, ce.code) |
| 55 | + assert.Equal(t, "a pending registration already exists for this account", ce.message) |
| 56 | + assert.Zero(t, notifier.received, "a duplicate must not email admins") |
| 57 | + store.AssertNumberOfCalls(t, "CreateAccountRegistration", 1) |
| 58 | +} |
| 59 | + |
| 60 | +// Errors that are not the duplicate sentinel must surface as a generic 500, |
| 61 | +// even when their text contains "duplicate", and must not leak the DB error. |
| 62 | +func TestSubmitRegistration_NonDuplicateErrors_Return500(t *testing.T) { |
| 63 | + cases := map[string]error{ |
| 64 | + "text mentions duplicate": errors.New( |
| 65 | + `duplicate: duplicate key value violates unique constraint "idx_account_registrations_pending_unique"`), |
| 66 | + "unique violation on another constraint": fmt.Errorf("failed to create account registration: %w", |
| 67 | + &pgconn.PgError{Code: "23505", ConstraintName: "account_registrations_pkey", |
| 68 | + Message: "duplicate key value violates unique constraint"}), |
| 69 | + "other database error": fmt.Errorf("failed to create account registration: %w", |
| 70 | + &pgconn.PgError{Code: "53300", Message: "too many connections"}), |
| 71 | + } |
| 72 | + for name, storeErr := range cases { |
| 73 | + t.Run(name, func(t *testing.T) { |
| 74 | + ctx := context.Background() |
| 75 | + store := new(MockConfigStore) |
| 76 | + store.On("CreateAccountRegistration", ctx, mock.Anything).Return(storeErr).Once() |
| 77 | + notifier := &countingRegistrationNotifier{} |
| 78 | + h := &Handler{config: store, emailNotifier: notifier} |
| 79 | + |
| 80 | + _, err := h.submitRegistration(ctx, submitRegistrationRequest()) |
| 81 | + |
| 82 | + require.Error(t, err) |
| 83 | + _, isClient := IsClientError(err) |
| 84 | + assert.False(t, isClient, "must not be reported as a client (409) error") |
| 85 | + status, body := h.handleRequestError(err) |
| 86 | + assert.Equal(t, 500, status) |
| 87 | + assert.Equal(t, map[string]string{"error": "Internal server error"}, body) |
| 88 | + assert.Zero(t, notifier.received, "a duplicate must not email admins") |
| 89 | + store.AssertNumberOfCalls(t, "CreateAccountRegistration", 1) |
| 90 | + }) |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +// A reference-token collision is retryable: the handler regenerates the token |
| 95 | +// and re-inserts instead of telling the submitter the account is registered. |
| 96 | +func TestSubmitRegistration_TokenCollision_RetriesWithNewToken(t *testing.T) { |
| 97 | + ctx := context.Background() |
| 98 | + store := new(MockConfigStore) |
| 99 | + var tokens []string |
| 100 | + collision := fmt.Errorf("%w: %w", config.ErrReferenceTokenCollision, |
| 101 | + &pgconn.PgError{Code: "23505", ConstraintName: "account_registrations_reference_token_key"}) |
| 102 | + record := func(args mock.Arguments) { |
| 103 | + tokens = append(tokens, args.Get(1).(*config.AccountRegistration).ReferenceToken) |
| 104 | + } |
| 105 | + store.On("CreateAccountRegistration", ctx, mock.Anything).Run(record).Return(collision).Once() |
| 106 | + store.On("CreateAccountRegistration", ctx, mock.Anything).Run(record).Return(nil).Once() |
| 107 | + h := &Handler{config: store} |
| 108 | + |
| 109 | + resp, err := h.submitRegistration(ctx, submitRegistrationRequest()) |
| 110 | + |
| 111 | + require.NoError(t, err) |
| 112 | + require.Len(t, tokens, 2) |
| 113 | + assert.NotEqual(t, tokens[0], tokens[1], "retry must use a fresh token") |
| 114 | + assert.Equal(t, map[string]string{"reference_token": tokens[1], "status": "pending"}, resp) |
| 115 | +} |
| 116 | + |
| 117 | +func TestSubmitRegistration_TokenCollision_GivesUpAs500(t *testing.T) { |
| 118 | + ctx := context.Background() |
| 119 | + store := new(MockConfigStore) |
| 120 | + collision := fmt.Errorf("%w: %w", config.ErrReferenceTokenCollision, |
| 121 | + &pgconn.PgError{Code: "23505", ConstraintName: "account_registrations_reference_token_key"}) |
| 122 | + store.On("CreateAccountRegistration", ctx, mock.Anything).Return(collision) |
| 123 | + h := &Handler{config: store} |
| 124 | + |
| 125 | + _, err := h.submitRegistration(ctx, submitRegistrationRequest()) |
| 126 | + |
| 127 | + require.ErrorIs(t, err, config.ErrReferenceTokenCollision) |
| 128 | + _, isClient := IsClientError(err) |
| 129 | + assert.False(t, isClient) |
| 130 | + store.AssertNumberOfCalls(t, "CreateAccountRegistration", maxReferenceTokenAttempts) |
| 131 | +} |
0 commit comments