Repository navigation
feat(db): read, change and delete a brand only within the person's brand access (00389) - #1879
Conversation
… and access helpers (00388)
BRAND-ACCESS PR 1 of 16: the data and the rule, no behaviour change.
Everyone starts with All brands, and no policy reads it yet.
- profiles.brand_scope ('all' | 'selected', default 'all'), set by the
server: 00374's guard refuses a person's own change; admins are always
'all' (a check, and a reset on promotion); leaving the organization
resets it to 'all'. A move straight into another organization keeps the
scope the update gives, so it never widens access by itself.
- member_brands (organization, person, brand, granted_by, granted_at),
one row per person and brand, gone with the brand, the person or the
organization; a trigger keeps the brand and the person in the row's
organization. The person reads their own rows, admins the
organization's; only the server writes. The rows go when the person
moves, leaves or gets All brands.
- invitations.brand_scope / brand_ids, checked against the organization.
- public.can_access_brand(brand, person default auth.uid()) and
public.user_brand_ids(): STABLE, SECURITY DEFINER, empty search path,
for authenticated and service_role only. Admin, All brands, a shared
brand or the demo brand, in the person's organization; another
person's id only for the service role.
- A brand added by a Selected-brands person is shared with them (after
insert trigger).
- web types, and member_brands on the demo coverage's skipped list.
- server/src/lib/brand-access-schema.test.js reads the migration.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…and access (00389) BRAND-ACCESS PR 2 of 16, on top of 00388. Nothing changes while everyone has All brands: for them each policy passes exactly the rows it passed before. - brands select: All-brands people (admins included) still match on the row's own organization_id, so a brand being added reads back (insert ... returning checks the select policy before the row is stored; a lookup by id such as can_access_brand(id) would refuse every new brand). Selected-brands people match on user_brand_ids(). - brands update and delete keep their role checks and add `id in (select public.user_brand_ids())`. Insert is unchanged. - The helper runs once per query (an uncorrelated hashed SubPlan); the three policies are to authenticated, since anon may not run it. - Every brand table's policy that reads its brand through brands narrows with this. server/src/lib/brand-access-policies.test.js fails on a brand table whose client policy neither reads brands nor calls the access rule; the 12 tables PR 3 fixes and the 16 server-only ones are listed there. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…manager can add one createBrand chooses the brand's id, inserts without asking for the row back, then reads it by id. Under 00389 a Selected-brands person sees a new brand only once the creator grant (00388, after insert) has shared it, and insert ... returning is checked against the select policy before that, so Add brand failed for them. 00389's comment now says so.
gkhngyk
left a comment
There was a problem hiding this comment.
Looks good with 2f5cc99: one fix commit on this branch, described below. Apply 00388 and 00389 before merging.
The fix: Add brand for a Selected-brands manager. createBrand did .insert(...).select().single(), i.e. insert … returning. PostgreSQL checks the returning row against the select policy before the after-insert creator grant (00388) runs, so a 'selected' manager got an RLS error on Add brand. The PR body listed this as a known limit for PR 12. It's a three-line change, so it ships here, before anyone can be narrowed:
createBrandpicks the brand id (crypto.randomUUID()), inserts without returning, then reads the row back by id. That read happens after the grant, so the person sees their new brand. Thebrand_domainsinsert after it works as before.- This follows the pattern from
insertOrganization(#1873). Nothing changes in the policies or the security model. - A new test in
web/src/lib/actions/brand.test.tschecks that the insert never asks for the row back and that the read-back filters on the chosen id. It fails without the fix. - 00389's comment now describes what createBrand does, not a later change.
schema.sqlwas rebuilt withbuild-schema.sh.
Other brand insert paths: onboarding and the New brand page both go through createBrand. The demo brand is created by the server with the service role, which bypasses RLS. Nothing else inserts into brands. updateBrand's update … returning is fine: the row is already visible to anyone allowed to update it.
Migrations: 00388 and 00389 match what prod has today. The old brands expressions are kept as-is, and the scope is added on top. There are no clashes with main. The only other open PRs that carry 00388/00389 are #1881 and #1888, which stack on this one. They will need a rebase onto the fixed head: #1881 also edits createBrand and brand.test.ts, in different hunks from this fix.
Checks: the PR merges cleanly on current main (main is already its ancestor).
- web vitest passes:
brand.test.ts,plan-row.test.ts, the New brand and onboarding page tests (31/31). - server vitest passes:
brand-access-policies,brand-access-schema, demo (145/145). tsc --noEmitpasses, and eslint and prettier are clean on the touched files.
Deploy order: either order works. The web fix works under the old and new policies. Apply 00388, then 00389, in one transaction.
gkhngyk
left a comment
There was a problem hiding this comment.
Merging in order with the other approved PRs. This head merges current main; its tree is what main will be after this squash, checked with the full server and web suites, tsc, lint, format and next build.
Summary
Brand-level access, PR 2: the
brandspolicies follow a person's brand access. Migration 00389. Stacked on #1878 (00388). Nothing changes while everyone isall, and dev showed the same counts before and after (below).00389
brandsselect:'all'people keep today's rule: the row's Account is theirs;'selected'people seeid in (select public.user_brand_ids()), which is evaluated once per query (hashed SubPlan).can_access_brand(id)per row: that would run per row, andinsert … returningchecks select before the row exists, which would break brand creation for everyone.not is_demokept.to authenticated. Service role and postgres bypass RLS, and anon already saw no brand.brandsfollows: 147 policies on 83 tables.server/src/lib/brand-access-policies.test.js:brandsor call the helpers;Known limit, by design: a
'selected'Manager'sinsert into brands … returningfails RLS, because the creator grant fires after the returning check. Nobody is'selected'until the Team UI (PR 12), and that PR creates brands withoutreturning, then reads them.Related issue
None. Brand-level access, PR 2 of ~16.
Type of change
feat— New featurefix— Bug fixchore— Maintenance / dependenciesdocs— Documentation onlyrefactor— Code change that neither fixes a bug nor adds a featuretest— Adding or updating testsHow to test
Applied on the dev database (00388, then 00389, each in one transaction) and checked inside rolled-back transactions.
'all'people (manager, analyst, admin): the counts on 8 tables equal postgres's, the same as before the migration. The tables arebrands,prompt_sets,prompts,competitors,insights_brand_daily,insights_prompt_daily,prompt_resultsandbrand_domains. Updates as before: Manager and Admin 1 row, Analyst 0, the demo brand 0.A
'selected'manager:brand_domainsinsert on it → RLS error, while the given brand works;user_brand_ids()= {given, demo};brand_scope→ 42501.Service role:
can_access_brand(given, mgr)→ t,(other, mgr)→ f.anon: 0 brands; the helpers → permission denied.
Timing (server-side median, dev):
allselectedinsights_kpi_seriesinsights_aggregates_dailyinsights_prompt_dailyselectbrandsselectallpeople the difference is noise:user_brand_ids()is "never executed", because the first OR branch decides.selectedpeople it adds about 0.3–0.4 ms per subquery.Checklist
yarn lintpasses (0 errors; 7 old warnings in files this PR doesn't touch)yarn typecheckpassesyarn format:checkpasseshelp/(or no user-visible change): no user-visible changeFor production (@gkhngyk): apply 00389 after 00388, in one transaction (
--include-all). No env or cron.Next, from this PR's review (in the spec; none of this affects anyone while everyone is
all):org_prompt_location_usage,maxBrands) must count the whole Account, not RLS-scoped rows;DOblocks, child tables withoutbrand_id,to authenticatedfor helper callers);brand_idsfrom non-Admins;member_brandscheck trigger.acceptInvitationwrites the scope and grants together; brand creation withoutreturning.🤖 Generated with Claude Code