diff --git a/hscontrol/oidc.go b/hscontrol/oidc.go index fa2607441..f7665519a 100644 --- a/hscontrol/oidc.go +++ b/hscontrol/oidc.go @@ -78,6 +78,10 @@ type AuthProviderOIDC struct { authCacheRegistrations atomic.Int64 authCache *expirable.LRU[string, AuthInfo] + // userMu makes the lookup and create in [AuthProviderOIDC.createOrUpdateUserFromClaim] + // atomic, so concurrent first logins of one identity share a single user. + userMu sync.Mutex + oidcProvider *oidc.Provider oauth2Config *oauth2.Config } @@ -648,6 +652,9 @@ func (a *AuthProviderOIDC) createOrUpdateUserFromClaim( c change.Change ) + a.userMu.Lock() + defer a.userMu.Unlock() + user, err = a.h.state.GetUserByOIDCIdentifier(claims.Identifier()) if err != nil && !errors.Is(err, db.ErrUserNotFound) { return nil, change.Change{}, fmt.Errorf("creating or updating user: %w", err) diff --git a/hscontrol/oidc_test.go b/hscontrol/oidc_test.go index 938985992..95b00d1a6 100644 --- a/hscontrol/oidc_test.go +++ b/hscontrol/oidc_test.go @@ -1512,6 +1512,52 @@ func TestOIDCLoginClearsUnverifiedEmail(t *testing.T) { assert.Empty(t, stored.Email) } +// Clients of a new OIDC user often log in at once; every callback must land +// on the one user instead of failing on the unique provider identifier. +func TestOIDCConcurrentFirstLoginCreatesOneUser(t *testing.T) { + app := createTestApp(t) + provider := &AuthProviderOIDC{h: app, cfg: &types.OIDCConfig{}} + claims := types.OIDCClaims{Iss: "https://idp.example.com", Sub: "racer", Username: "racer"} + + const logins = 8 + + var ( + start sync.WaitGroup + done sync.WaitGroup + ids [logins]uint + errs [logins]error + ) + + start.Add(1) + + for i := range logins { + done.Go(func() { + start.Wait() + + c := claims + + user, _, err := provider.createOrUpdateUserFromClaim(&c) + if user != nil { + ids[i] = user.ID + } + + errs[i] = err + }) + } + + start.Done() + done.Wait() + + for i := range logins { + require.NoError(t, errs[i], "login %d", i) + assert.Equal(t, ids[0], ids[i], "login %d", i) + } + + users, err := app.state.ListAllUsers() + require.NoError(t, err) + assert.Len(t, users, 1) +} + func TestOIDCCallbackDispatchesUserIdentityChange(t *testing.T) { b := newOIDCBrowser(t) provider, ok := b.app.authProvider.(*AuthProviderOIDC)