Repository navigation
feat(backend): track first organization onboarding in Bento #2841
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 11 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
65c620c
feat(backend): track first organization lifecycle in Bento
WcaleNieWolny d61580a
test(backend): strengthen Bento lifecycle coverage
WcaleNieWolny 6c6f9f6
fix(backend): harden Bento lifecycle updates
WcaleNieWolny 526bd93
fix(backend): fix Bento lifecycle ordering
WcaleNieWolny b25a1ff
fix(backend): require one queued Bento email change
WcaleNieWolny 0ef08e6
fix(backend): suppress first-org recovery on email changes
WcaleNieWolny cda36d1
docs: document first-org recovery safety guard
WcaleNieWolny 03b4509
feat(db): queue active organization access changes
WcaleNieWolny a543df5
fix(backend): harden first-org lifecycle ordering
WcaleNieWolny 56cd6e1
fix(backend): address first-org review findings
WcaleNieWolny 8811d6a
fix(backend): harden first-org trigger validation
WcaleNieWolny 15f704b
fix(backend): harden onboarding deletion races
WcaleNieWolny 335af5b
fix(backend): harden onboarding cleanup retries
WcaleNieWolny 0154b7c
fix(backend): reconcile Bento deletion races
WcaleNieWolny 7df4311
test(backend): assert lock-timeout provisioning
WcaleNieWolny f24c3c1
fix(backend): abort timed-out Bento cleanup
WcaleNieWolny 4d0f4d2
test(backend): prove Bento abort ordering
WcaleNieWolny 6c3f285
fix(backend): preserve Bento reconciliation errors
WcaleNieWolny 476cade
fix(backend): harden Bento lifecycle ordering
WcaleNieWolny File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
18 changes: 18 additions & 0 deletions
18
supabase/functions/_backend/triggers/on_user_org_access.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| import type { MiddlewareKeyVariables } from '../utils/hono.ts' | ||
| import type { Database } from '../utils/supabase.types.ts' | ||
| import { Hono } from 'hono/tiny' | ||
|
WcaleNieWolny marked this conversation as resolved.
Resolved
|
||
| import { z } from 'zod' | ||
| import { syncBentoFirstOrgOnRoleBindingWrite } from '../utils/bento_first_org.ts' | ||
| import { BRES, middlewareAPISecret, simpleError, triggerValidator } from '../utils/hono.ts' | ||
|
|
||
| export const app = new Hono<MiddlewareKeyVariables>() | ||
|
|
||
| app.post('/', middlewareAPISecret, triggerValidator('role_bindings', ['INSERT', 'UPDATE']), async (c) => { | ||
| const record = c.get('webhookBody') as Partial<Database['public']['Tables']['role_bindings']['Row']> | ||
| const bindingId = z.uuid().safeParse(record.id) | ||
| if (!bindingId.success) | ||
| throw simpleError('invalid_payload', 'Invalid role binding id', { id: record.id }) | ||
|
|
||
| await syncBentoFirstOrgOnRoleBindingWrite(c, bindingId.data) | ||
| return c.json(BRES) | ||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,176 @@ | ||
| import type { Context } from 'hono' | ||
| import type { MiddlewareKeyVariables } from './hono.ts' | ||
| import type { Database } from './supabase.types.ts' | ||
| import { syncBentoSubscriberTags, trackBentoEvent } from './bento.ts' | ||
| import { quickError } from './hono.ts' | ||
| import { closeClient, getPgClient } from './pg.ts' | ||
|
|
||
| export const BENTO_AWAITING_FIRST_ORG_TAG = 'onboarding:awaiting_first_org' | ||
| // Permanent safety opt-out: never remove this tag. The Bento recovery workflow | ||
| // must require it to be absent immediately before sending a recovery email. | ||
| export const BENTO_FIRST_ORG_RECOVERY_SUPPRESSED_TAG = 'onboarding:first_org_recovery_suppressed' | ||
| export const BENTO_REGISTERED_WITHOUT_ORG_EVENT = 'user:registered_without_org' | ||
| export const BENTO_JOINED_ORG_EVENT = 'user:joined_org' | ||
|
|
||
| interface CurrentRoleBinding { | ||
| email: string | null | ||
| granted_at: Date | ||
| id: string | ||
| is_active: boolean | ||
| is_direct: boolean | ||
| org_id: string | null | ||
| principal_id: string | ||
| principal_type: string | ||
| scope_type: string | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| export function normalizeBentoEmail(email: string) { | ||
| return email.trim().toLowerCase() | ||
| } | ||
|
|
||
| function ensureBentoDelivery(result: boolean | undefined, operation: string) { | ||
| if (result === false) | ||
| quickError(500, 'bento_lifecycle_delivery_failed', 'Bento lifecycle delivery failed', { operation }) | ||
| } | ||
|
|
||
| async function setAwaitingFirstOrgTag(c: Context, email: string, awaiting: boolean) { | ||
| const result = await syncBentoSubscriberTags(c, { | ||
| email, | ||
| segments: awaiting ? [BENTO_AWAITING_FIRST_ORG_TAG] : [], | ||
| deleteSegments: awaiting ? [] : [BENTO_AWAITING_FIRST_ORG_TAG], | ||
| }) | ||
| ensureBentoDelivery(result, awaiting ? 'add_awaiting_first_org_tag' : 'remove_awaiting_first_org_tag') | ||
| } | ||
|
|
||
| export async function syncBentoFirstOrgOnEmailChange(c: Context, oldEmail: string, newEmail: string) { | ||
| const aliases = [...new Set([oldEmail, newEmail].map(normalizeBentoEmail).filter(Boolean))] | ||
| return await syncBentoSubscriberTags(c, aliases.map(email => ({ | ||
| email, | ||
| segments: [BENTO_FIRST_ORG_RECOVERY_SUPPRESSED_TAG], | ||
| deleteSegments: [BENTO_AWAITING_FIRST_ORG_TAG], | ||
| }))) | ||
| } | ||
|
|
||
| async function hasActiveDirectOrgAccess(pgPool: ReturnType<typeof getPgClient>, userId: string) { | ||
| const pgClient = await pgPool.connect() | ||
| try { | ||
| const result = await pgClient.query<{ id: string }>( | ||
| `SELECT id | ||
| FROM public.role_bindings | ||
| WHERE principal_type = 'user' | ||
| AND principal_id = $1::uuid | ||
| AND scope_type = 'org' | ||
| AND org_id IS NOT NULL | ||
| AND is_direct IS TRUE | ||
| AND (expires_at IS NULL OR expires_at > pg_catalog.now()) | ||
| LIMIT 1`, | ||
| [userId], | ||
| ) | ||
| return result.rows.length > 0 | ||
| } | ||
| finally { | ||
| // General-backend Pools are request-scoped and closeClient intentionally | ||
| // does not end them in workerd. Destroy the checked-out socket at the query | ||
| // boundary so it cannot survive across Bento I/O or request teardown. | ||
| pgClient.release(true) | ||
| } | ||
| } | ||
|
|
||
| export async function syncBentoFirstOrgOnUserCreate( | ||
| c: Context<MiddlewareKeyVariables>, | ||
| user: Database['public']['Tables']['users']['Row'], | ||
| ) { | ||
| const email = normalizeBentoEmail(user.email) | ||
|
|
||
| if (user.created_via_invite) { | ||
| await setAwaitingFirstOrgTag(c, email, false) | ||
| return | ||
| } | ||
|
|
||
| const pgPool = getPgClient(c) | ||
| try { | ||
| if (await hasActiveDirectOrgAccess(pgPool, user.id)) { | ||
| await setAwaitingFirstOrgTag(c, email, false) | ||
| return | ||
| } | ||
|
|
||
| await setAwaitingFirstOrgTag(c, email, true) | ||
|
|
||
| if (await hasActiveDirectOrgAccess(pgPool, user.id)) { | ||
| await setAwaitingFirstOrgTag(c, email, false) | ||
| return | ||
| } | ||
|
|
||
| const result = await trackBentoEvent(c, email, { | ||
| user_id: user.id, | ||
| registered_at: user.created_at, | ||
| created_via_invite: false, | ||
| }, BENTO_REGISTERED_WITHOUT_ORG_EVENT) | ||
| ensureBentoDelivery(result, 'registered_without_org_event') | ||
|
WcaleNieWolny marked this conversation as resolved.
Resolved
|
||
| } | ||
| finally { | ||
| await closeClient(c, pgPool) | ||
| } | ||
| } | ||
|
|
||
| export async function syncBentoFirstOrgOnRoleBindingWrite( | ||
| c: Context<MiddlewareKeyVariables>, | ||
| roleBindingId: string, | ||
| ) { | ||
| const pgPool = getPgClient(c) | ||
| try { | ||
| let binding: CurrentRoleBinding | undefined | ||
| const pgClient = await pgPool.connect() | ||
| try { | ||
| const result = await pgClient.query<CurrentRoleBinding>( | ||
| `SELECT | ||
| binding.id, | ||
| binding.principal_type, | ||
| binding.principal_id, | ||
| binding.scope_type, | ||
| binding.org_id, | ||
| binding.granted_at, | ||
| binding.is_direct, | ||
| (binding.expires_at IS NULL OR binding.expires_at > pg_catalog.now()) AS is_active, | ||
| users.email | ||
| FROM public.role_bindings AS binding | ||
| LEFT JOIN public.users AS users | ||
| ON users.id = binding.principal_id | ||
| WHERE binding.id = $1::uuid | ||
| LIMIT 1`, | ||
| [roleBindingId], | ||
| ) | ||
| binding = result.rows[0] | ||
| } | ||
| finally { | ||
| // See hasActiveDirectOrgAccess: destroy this request-scoped socket before | ||
| // the handler crosses the network boundary into Bento. | ||
| pgClient.release(true) | ||
| } | ||
|
|
||
| if ( | ||
| !binding | ||
| || binding.principal_type !== 'user' | ||
|
Check warning on line 153 in supabase/functions/_backend/utils/bento_first_org.ts
|
||
| || binding.scope_type !== 'org' | ||
| || !binding.org_id | ||
| || binding.is_direct !== true | ||
| || binding.is_active !== true | ||
| || !binding.email | ||
| ) { | ||
| return | ||
| } | ||
|
|
||
| const email = normalizeBentoEmail(binding.email) | ||
| await setAwaitingFirstOrgTag(c, email, false) | ||
| const result = await trackBentoEvent(c, email, { | ||
| user_id: binding.principal_id, | ||
| org_id: binding.org_id, | ||
| role_binding_id: binding.id, | ||
| joined_at: binding.granted_at.toISOString(), | ||
| }, BENTO_JOINED_ORG_EVENT) | ||
| ensureBentoDelivery(result, 'joined_org_event') | ||
| } | ||
| finally { | ||
| await closeClient(c, pgPool) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.