Skip to content
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
104 changes: 104 additions & 0 deletions internal/identity/provision_adopt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -492,3 +492,107 @@ func TestProvisionRefusesSecondPrincipalFromSameIssuer(t *testing.T) {
}
assertUnmapped(t, store, "tcusr_second")
}

// Different external refs must not both pass the absence check for the same
// issuer and Google holder. Stop the first insertion after its check so the
// second attempt overlaps deterministically. Without holder serialization both
// requests reach this trigger; with it, the second waits on the holder instead.
func TestProvisionConcurrentAdoptionsDifferentRefsSameIssuer(t *testing.T) {
pool := testutil.TestDB(t)
store := identity.NewStore(pool)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
existing := newDirectSignup(t, store, "[email protected]")

if _, err := pool.Exec(ctx, `
CREATE FUNCTION test_adoption_insert_barrier() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
PERFORM pg_advisory_xact_lock(1170001);
RETURN NEW;
END $$;
CREATE TRIGGER test_adoption_insert_barrier
BEFORE INSERT ON external_principal_mappings
FOR EACH ROW EXECUTE FUNCTION test_adoption_insert_barrier()`); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cleanupCancel()
if _, err := pool.Exec(cleanupCtx, `
DROP TRIGGER IF EXISTS test_adoption_insert_barrier ON external_principal_mappings;
DROP FUNCTION IF EXISTS test_adoption_insert_barrier()`); err != nil {
t.Errorf("remove adoption barrier: %v", err)
}
})

blocker, err := pool.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer blocker.Rollback(context.Background())
if _, err := blocker.Exec(ctx, `SELECT pg_advisory_xact_lock(1170001)`); err != nil {
t.Fatal(err)
}

type result struct {
user *identity.User
created, adopted bool
err error
}
done := make(chan result, 2)
for _, ref := range []string{"tcusr_concurrent_first", "tcusr_concurrent_second"} {
go func(ref string) {
u, created, adopted, err := store.ProvisionUserAdopting(ctx,
ref, "[email protected]", "", testIssuer, adoptGoogleSub)
done <- result{u, created, adopted, err}
}(ref)
}

deadline := time.Now().Add(10 * time.Second)
for {
var waiters int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM pg_stat_activity
WHERE datname = current_database() AND wait_event_type = 'Lock'`).Scan(&waiters); err != nil {
t.Fatal(err)
}
if waiters == 2 {
break
}
if time.Now().After(deadline) {
t.Fatalf("got %d blocked adoption requests, want two before releasing barrier", waiters)
}
time.Sleep(10 * time.Millisecond)
}
if err := blocker.Rollback(ctx); err != nil {
t.Fatal(err)
}

successes, conflicts := 0, 0
for range 2 {
select {
case got := <-done:
switch {
case got.err == nil:
successes++
if got.user == nil || got.user.ID != existing.ID || got.created || !got.adopted {
t.Errorf("successful adoption = %+v, want existing user adopted", got)
}
case errors.Is(got.err, identity.ErrExternalPrincipalConflict):
conflicts++
default:
t.Errorf("unexpected adoption error: %v", got.err)
}
case <-ctx.Done():
t.Fatal("concurrent adoptions did not finish: ", ctx.Err())
}
}
var mappings int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM external_principal_mappings
WHERE issuer = $1 AND user_id = $2`, testIssuer, existing.ID).Scan(&mappings); err != nil {
t.Fatal(err)
}
if successes != 1 || conflicts != 1 || mappings != 1 {
t.Fatalf("concurrent different-ref adoption: successes=%d conflicts=%d mappings=%d; want 1, 1, 1",
successes, conflicts, mappings)
}
}
14 changes: 8 additions & 6 deletions internal/identity/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -6356,9 +6356,10 @@ func (s *Store) ProvisionUserAdopting(ctx context.Context, externalRef, email, n
// error). It must run BEFORE the insert: the insert's unique violation would
// abort the transaction.
//
// Every read takes FOR SHARE, as AttachExternalPrincipal does: it conflicts
// with the trash/restore/purge FOR NO KEY UPDATE, so an account cannot be
// trashed between this check and the mapping insert.
// A matching replay holds FOR SHARE and returns immediately. New adoption
// holds FOR NO KEY UPDATE before checking issuer ownership, serializing
// competing refs without conflicting with the mapping insert's FK key-share
// lock. Both modes exclude trash/restore/purge while the mapping is written.
func (s *Store) adoptableUserTx(ctx context.Context, tx pgx.Tx, email, googleSubject, externalIssuer, externalRef string) (*User, error) {
// Replay first, by the mapping: an earlier adoption of this pair resolves
// to the same user even if that user's email has since changed (an
Expand All @@ -6367,15 +6368,16 @@ func (s *Store) adoptableUserTx(ctx context.Context, tx pgx.Tx, email, googleSub
mapped, err := scanUser(tx.QueryRow(ctx,
`SELECT `+userColumns+` FROM users
WHERE id = (SELECT user_id FROM external_principal_mappings WHERE issuer = $1 AND subject = $2)
FOR SHARE`, externalIssuer, externalRef))
if err == nil && mapped.DeletedAt == nil && mapped.GoogleSubject == googleSubject {
AND google_subject = $3 AND deleted_at IS NULL
FOR SHARE`, externalIssuer, externalRef, googleSubject))
if err == nil {
return mapped, nil
}
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return nil, err
}
holder, err := scanUser(tx.QueryRow(ctx,
`SELECT `+userColumns+` FROM users WHERE email = $1 FOR SHARE`, email))
`SELECT `+userColumns+` FROM users WHERE email = $1 FOR NO KEY UPDATE`, email))
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
Expand Down
Loading