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 9 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
25 changes: 25 additions & 0 deletions
25
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,25 @@ | ||
| import type { MiddlewareKeyVariables } from '../utils/hono.ts' | ||
| import { Hono } from 'hono/tiny' | ||
|
WcaleNieWolny marked this conversation as resolved.
Outdated
|
||
| import { syncBentoFirstOrgOnRoleBindingWrite } from '../utils/bento_first_org.ts' | ||
| import { BRES, middlewareAPISecret, parseBody, simpleError } from '../utils/hono.ts' | ||
|
|
||
| interface RoleBindingWritePayload { | ||
| record?: { id?: string | null } | null | ||
| table?: string | ||
| type?: string | ||
| } | ||
|
|
||
| export const app = new Hono<MiddlewareKeyVariables>() | ||
|
|
||
| app.post('/', middlewareAPISecret, async (c) => { | ||
| const payload = await parseBody<RoleBindingWritePayload>(c) | ||
| if (payload.table !== 'role_bindings') | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
Outdated
|
||
| throw simpleError('table_not_match', 'Not role_bindings', { payload }) | ||
| if (payload.type !== 'INSERT' && payload.type !== 'UPDATE') | ||
| throw simpleError('type_not_match', 'Not INSERT or UPDATE', { payload }) | ||
| if (!payload.record?.id) | ||
| throw simpleError('invalid_payload', 'Missing role binding id', { payload }) | ||
|
|
||
| await syncBentoFirstOrgOnRoleBindingWrite(c, payload.record.id) | ||
| 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,171 @@ | ||
| 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: string | ||
| 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.
|
||
|
|
||
| function normalizedEmail(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(normalizedEmail).filter(Boolean))] | ||
| return await syncBentoSubscriberTags(c, aliases.map(email => ({ | ||
| email, | ||
| segments: [BENTO_FIRST_ORG_RECOVERY_SUPPRESSED_TAG], | ||
| deleteSegments: [BENTO_AWAITING_FIRST_ORG_TAG], | ||
| }))) | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| 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 { | ||
| pgClient.release(true) | ||
| } | ||
| } | ||
|
WcaleNieWolny marked this conversation as resolved.
Outdated
|
||
|
|
||
| export async function syncBentoFirstOrgOnUserCreate( | ||
| c: Context<MiddlewareKeyVariables>, | ||
| user: Database['public']['Tables']['users']['Row'], | ||
| ) { | ||
| const email = normalizedEmail(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.
Outdated
|
||
| } | ||
| 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 { | ||
| pgClient.release(true) | ||
| } | ||
|
|
||
| if ( | ||
| !binding | ||
| || binding.principal_type !== 'user' | ||
|
Check warning on line 148 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 = normalizedEmail(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, | ||
| }, 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
57 changes: 57 additions & 0 deletions
57
supabase/migrations/20260803161022_on_user_org_access_queue.sql
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,57 @@ | ||
| -- Feed active direct user-to-organization role bindings into the existing | ||
| -- function queue dispatcher. | ||
| -- | ||
| -- Execution model: | ||
| -- - Where: row-level AFTER INSERT / activation-relevant UPDATE trigger on | ||
| -- public.role_bindings. | ||
| -- - Frequency: once for each new row that currently grants active direct | ||
| -- organization access. Non-qualifying rows are rejected by the trigger WHEN | ||
| -- clause before the trigger function runs. | ||
| -- - Roles: any role allowed to write role_bindings; the existing generic | ||
| -- trigger function runs as SECURITY DEFINER. | ||
| -- - Cardinality: O(1) pgmq.send per qualifying row. The trigger performs no | ||
| -- table scan; the queue handler reloads the binding by its primary key. | ||
|
|
||
| DO $$ | ||
| BEGIN | ||
| IF NOT EXISTS ( | ||
| SELECT 1 | ||
| FROM pgmq.list_queues() | ||
| WHERE queue_name = 'on_user_org_access' | ||
| ) THEN | ||
| PERFORM pgmq.create('on_user_org_access'); | ||
| END IF; | ||
| END; | ||
| $$; | ||
|
|
||
| DROP TRIGGER IF EXISTS on_user_org_access ON public.role_bindings; | ||
|
|
||
| CREATE TRIGGER on_user_org_access | ||
| AFTER INSERT OR UPDATE OF | ||
| principal_type, | ||
| principal_id, | ||
| scope_type, | ||
| org_id, | ||
| expires_at, | ||
| is_direct | ||
| ON public.role_bindings | ||
| FOR EACH ROW | ||
| WHEN ( | ||
| new.principal_type = 'user' | ||
| AND new.scope_type = 'org' | ||
| AND new.org_id IS NOT NULL | ||
| AND new.is_direct IS TRUE | ||
| AND (new.expires_at IS NULL OR new.expires_at > pg_catalog.now()) | ||
| ) | ||
| EXECUTE FUNCTION public.trigger_http_queue_post_to_function( | ||
| 'on_user_org_access' | ||
| ); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| UPDATE public.cron_tasks | ||
| SET | ||
| target = (target::jsonb || '["on_user_org_access"]'::jsonb)::text, | ||
| updated_at = pg_catalog.now() | ||
| WHERE | ||
| name = 'high_frequency_queues' | ||
| AND task_type = 'function_queue'::public.cron_task_type | ||
| AND NOT (target::jsonb ? 'on_user_org_access'); | ||
|
WcaleNieWolny marked this conversation as resolved.
Outdated
|
||
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.