hscontrol: serialise OIDC user lookup and create

Concurrent first logins of one identity both missed the lookup and
both created; the loser hit the unique index and returned 500.
This commit is contained in:
Kristoffer Dalby committed 2026-11-11 17:07:35 +01:00
1 parent 687bb762e0
commit 8b711055fb
2 files changed
+53

No files matched your search

+7
View File
@@ -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)
+46
View File
@@ -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)