Skip to content

feat(db): read, change and delete a brand only within the person's brand access (00389) - #1879

Merged
gkhngyk merged 4 commits into
ansvisor:mainfrom
cihan-gyk:feature/brand-access-brands-rls
Oct 31, 2026
Merged

gkhngyk merged 4 commits into
ansvisor:mainfrom
cihan-gyk:feature/brand-access-brands-rls

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

Brand-level access, PR 2: the brands policies follow a person's brand access. Migration 00389. Stacked on #1878 (00388). Nothing changes while everyone is all, and dev showed the same counts before and after (below).

00389

  • brands select:
    • 'all' people keep today's rule: the row's Account is theirs;
    • 'selected' people see id in (select public.user_brand_ids()), which is evaluated once per query (hashed SubPlan).
    • Not can_access_brand(id) per row: that would run per row, and insert … returning checks select before the row exists, which would break brand creation for everyone.
  • update / delete: the same scope added; role checks and not is_demo kept.
  • insert: unchanged.
  • The three policies are to authenticated. Service role and postgres bypass RLS, and anon already saw no brand.
  • Every policy that reaches a brand through brands follows: 147 policies on 83 tables.
  • Coverage test server/src/lib/brand-access-policies.test.js:
    • every policy on a brand table must read brands or call the helpers;
    • the 12 tables known to look only at the Account or the user are listed for PR 3, and the 16 server-only tables are listed too;
    • it fails on a new Account-only policy.

Known limit, by design: a 'selected' Manager's insert into brands … returning fails RLS, because the creator grant fires after the returning check. Nobody is 'selected' until the Team UI (PR 12), and that PR creates brands without returning, then reads them.

Related issue

None. Brand-level access, PR 2 of ~16.

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How 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 are brands, prompt_sets, prompts, competitors, insights_brand_daily, insights_prompt_daily, prompt_results and brand_domains. Updates as before: Manager and Admin 1 row, Analyst 0, the demo brand 0.

A 'selected' manager:

  • sees only the brand given to them, plus the demo brand;
  • another brand's 142 child rows read as 0;
  • update on that brand → 0 rows;
  • brand_domains insert on it → RLS error, while the given brand works;
  • user_brand_ids() = {given, demo};
  • writing their own 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):

Query Before After, all After, selected
insights_kpi_series 7.48 ms 7.49 ms 8.65 ms
insights_aggregates_daily 2.71 ms 2.60 ms 3.14 ms
insights_prompt_daily select 0.62 ms 0.66 ms 1.04 ms
brands select 0.18 ms 0.21 ms 0.58 ms
  • For all people the difference is noise: user_brand_ids() is "never executed", because the first OR branch decides.
  • For selected people it adds about 0.3–0.4 ms per subquery.

Checklist

  • Branch follows the naming convention
  • Commits follow Conventional Commits
  • yarn lint passes (0 errors; 7 old warnings in files this PR doesn't touch)
  • yarn typecheck passes
  • yarn format:check passes
  • Changes are focused — one concern per PR
  • Help article updated under help/ (or no user-visible change): no user-visible change

For 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):

  • PR 3:
    • plan quotas (org_prompt_location_usage, maxBrands) must count the whole Account, not RLS-scoped rows;
    • harden the coverage test (OR branches, policies inside DO blocks, child tables without brand_id, to authenticated for helper callers);
    • hide invitations' brand_ids from non-Admins;
    • lock the profile row in the member_brands check trigger.
  • PR 12: acceptInvitation writes the scope and grants together; brand creation without returning.
  • Order: do Google per brand (PR 14) before PR 12.

🤖 Generated with Claude Code

cihan-gyk and others added 2 commits October 31, 2026 01:39
… 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
gkhngyk previously approved these changes Oct 31, 2026

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  • createBrand picks 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. The brand_domains insert 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.ts checks 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.sql was rebuilt with build-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 --noEmit passes, 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 gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@gkhngyk
gkhngyk merged commit 6be014b into ansvisor:main Oct 31, 2026
4 of 5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants