Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
c988f2a
fix: possible race condition where multiple organizations could be cr…
wilsonrivera Aug 22, 2025
8db60b6
chore: remove `console.log`
wilsonrivera Aug 22, 2025
52a85e9
chore: create organization in two steps without lock
wilsonrivera Aug 22, 2025
4f41451
chore: fix incorrect variable
wilsonrivera Aug 22, 2025
cc38fe3
chore: remove fake delay
wilsonrivera Aug 22, 2025
c393048
chore: use transaction for org creation
wilsonrivera Aug 22, 2025
24a33fd
Merge branch 'main' into wilson/eng-7670-organization-created-twice
wilsonrivera Aug 25, 2025
af7ebe1
chore: use transaction lock
wilsonrivera Aug 25, 2025
169bc29
chore: introduce lighter method to check if user is already member of…
wilsonrivera Aug 25, 2025
1e29919
Merge branch 'main' into wilson/eng-7670-organization-created-twice
wilsonrivera Aug 25, 2025
a113f8b
Merge branch 'main' into wilson/eng-7670-organization-created-twice
wilsonrivera Sep 3, 2025
ce68d56
Merge branch 'main' into wilson/eng-7670-organization-created-twice
wilsonrivera Sep 3, 2025
d33dc79
Merge branch 'main' into wilson/eng-7670-organization-created-twice
wilsonrivera Sep 10, 2025
120dc60
Merge branch 'main' into wilson/eng-7670-organization-created-twice
wilsonrivera Sep 30, 2025
d0561df
chore: fast exit when the lock already exists
wilsonrivera Sep 30, 2025
e5971f7
chore: liting
wilsonrivera Sep 30, 2025
6be46ba
Merge branch 'main' into wilson/eng-7670-organization-created-twice
wilsonrivera Oct 1, 2025
e07d6e1
Merge branch 'main' into wilson/eng-7670-organization-created-twice
wilsonrivera Oct 1, 2025
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
117 changes: 75 additions & 42 deletions controlplane/src/core/controllers/auth.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { FastifyPluginCallback } from 'fastify';
import fp from 'fastify-plugin';
import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
import { eq } from 'drizzle-orm';
import { eq, sql } from 'drizzle-orm';
import { lru } from 'tiny-lru';
import { uid } from 'uid';
import { PlatformEventName } from '@wundergraph/cosmo-connect/dist/notifications/events_pb';
Expand Down Expand Up @@ -255,64 +255,97 @@ const plugin: FastifyPluginCallback<AuthControllerOptions> = function Auth(fasti
return insertedSessions[0];
});

const orgs = await opts.organizationRepository.memberships({
userId,
});
const orgs = await opts.db.transaction(async (tx) => {
const advisoryLockRows = await tx.execute(
sql`select pg_try_advisory_xact_lock(hashtext(${userId})) as acquired`,
);

if (!advisoryLockRows?.[0]?.acquired) {
// We need to identify when we failed to acquire the lock because another request already acquired it
return -1;
}

if (orgs.length === 0) {
const orgRepo = new OrganizationRepository(req.log, tx, opts.defaultBillingPlanId);

// Check if the user is already a member of at least one organization
const existingMemberships = await tx
.select({ one: sql<number>`1`.as('one') })
.from(organizationsMembers)
.where(eq(organizationsMembers.userId, userId))
.limit(1)
.execute();

if (existingMemberships.length > 0) {
return existingMemberships.length;
}

// Authenticate on Keycloak and create the organization group
await opts.keycloakClient.authenticateClient();

const organizationSlug = uid(8);

const [kcRootGroupId, kcCreatedGroups] = await opts.keycloakClient.seedGroup({
userID: userId,
organizationSlug,
realm: opts.keycloakRealm,
});

await opts.db.transaction(async (tx) => {
const orgRepo = new OrganizationRepository(req.log, tx, opts.defaultBillingPlanId);
const orgGroupRepo = new OrganizationGroupRepository(tx);

const insertedOrg = await orgRepo.createOrganization({
organizationName: userEmail.split('@')[0],
organizationSlug,
ownerID: userId,
kcGroupId: kcRootGroupId,
});
// Create the new organization and add the user as a member of the organization
const insertedOrg = await orgRepo.createOrganization({
organizationName: userEmail.split('@')[0],
organizationSlug,
ownerID: userId,
kcGroupId: kcRootGroupId,
});

const orgMember = await orgRepo.addOrganizationMember({
organizationID: insertedOrg.id,
userID: userId,
});
const orgMember = await orgRepo.addOrganizationMember({
organizationID: insertedOrg.id,
userID: userId,
});

await orgGroupRepo.importKeycloakGroups({
organizationId: insertedOrg.id,
kcGroups: kcCreatedGroups,
});
// Create the organization groups
const orgGroupRepo = new OrganizationGroupRepository(tx);

const orgAdminGroup = await orgGroupRepo.byName({
organizationId: insertedOrg.id,
name: 'admin',
});
await orgGroupRepo.importKeycloakGroups({
organizationId: insertedOrg.id,
kcGroups: kcCreatedGroups,
});

if (orgAdminGroup) {
await orgGroupRepo.addUserToGroup({
organizationMemberId: orgMember.id,
groupId: orgAdminGroup.groupId,
});
}
const orgAdminGroup = await orgGroupRepo.byName({
organizationId: insertedOrg.id,
name: 'admin',
});

const namespaceRepo = new NamespaceRepository(tx, insertedOrg.id);
const ns = await namespaceRepo.create({
name: DefaultNamespace,
createdBy: userId,
if (orgAdminGroup) {
await orgGroupRepo.addUserToGroup({
organizationMemberId: orgMember.id,
groupId: orgAdminGroup.groupId,
});
if (!ns) {
throw new Error(`Could not create ${DefaultNamespace} namespace`);
}
}

// Create the default namespace for the organization
const namespaceRepo = new NamespaceRepository(tx, insertedOrg.id);
const ns = await namespaceRepo.create({
name: DefaultNamespace,
createdBy: userId,
});

if (!ns) {
throw new Error(`Could not create ${DefaultNamespace} namespace`);
}

// We return an empty even when we just created the organization, that way we can still send the
// user registered webhook and prompt the user to migrate
return 0;
});

if (orgs === -1) {
// We failed to acquire the lock, so we need to retry the request
await res.code(429).send('Slow down');
return;
}

if (orgs === 0) {
// Send a notification to the platform that a new user has been created
opts.platformWebhooks.send(PlatformEventName.USER_REGISTER_SUCCESS, {
user_id: userId,
user_email: userEmail,
Expand Down Expand Up @@ -343,7 +376,7 @@ const plugin: FastifyPluginCallback<AuthControllerOptions> = function Auth(fasti
} else {
res.redirect(opts.webBaseUrl);
}
} else if (orgs.length === 0) {
} else if (orgs === 0) {
res.redirect(opts.webBaseUrl + '?migrate=true');
} else {
res.redirect(opts.webBaseUrl);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,13 @@ export class OrganizationRepository {
return org;
}

public async updateOrganization(input: { id: string; slug?: string; name?: string }) {
public async updateOrganization(input: { id: string; slug?: string; name?: string; kcGroupId?: string }) {
await this.db
.update(organizations)
.set({
name: input.name,
slug: input.slug,
kcGroupId: input.kcGroupId,
})
.where(eq(organizations.id, input.id))
.execute();
Expand Down
7 changes: 6 additions & 1 deletion controlplane/test/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { describe, expect, test } from 'vitest';
import { isValidLabelMatchers, mergeUrls, normalizeLabelMatchers, isGoogleCloudStorageUrl } from '../src/core/util.js';
import {
isValidLabelMatchers,
mergeUrls,
normalizeLabelMatchers,
isGoogleCloudStorageUrl,
} from '../src/core/util.js';

describe('Utils', () => {
test('isValidLabelMatchers', () => {
Expand Down