Skip to content

feat(db): keep the Account-wide brand tables, quotas and invitations within brand access (00390, 00424) - #1881

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

gkhngyk merged 7 commits into
ansvisor:mainfrom
cihan-gyk:feature/brand-access-rls-2

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

Brand-level access, PR 3: the tables and functions that looked only at the Account or the user now follow a person's brand access. Also: plan quotas, invitations, and a tighter coverage test. Migrations 00390 (Account-level) and 00424 (Chat tables; they're created in 00400–00422, so the change must sort after them). Stacked on #1879. Nothing changes while everyone is all; the one deliberate exception is invitations (below).

00390

  • prompt_usage_counters, content_draft_deliveries and agent_conversations (and agent_messages through it) add brand_id in (select public.user_brand_ids()), to authenticated.
  • content_draft_member() checks can_access_brand(d.brand_id). The 10 policies that use it are to authenticated.
  • Quotas count the whole Account, not RLS-scoped rows. Otherwise a Selected-brands person could pass the plan's limits:
    • org_prompt_location_usage becomes membership-checked SECURITY DEFINER. Brands the caller can't see are summed into one brand_id = null row, so totals stay whole and no hidden brand is named.
    • prompt_usage_summary becomes SECURITY DEFINER and checks brand access.
    • New org_brand_count() for maxBrands.
    • Web: lib/plan-brand-count.ts, used by createBrand and the Brands page. It falls back to the old count only on PGRST202/42883 (deploy order).
  • Invitations: "Members can view org invitations" becomes "Admins can view org invitations". team.ts listInvitations reads through the server with explicit columns (no token, no brand_ids), so Members still see the same Team list.
  • New helper user_has_all_brands(): true for Admins and all, STABLE, SECURITY DEFINER, search_path = ''.
  • The member_brands check trigger locks the profile row (for share).

00424 (Chat):

  • Covered tables: chat_conversations (own, shared, agent run), chat_agent_runs, chat_why_analyses, chat_files, chat_activity_log, chat_access_requests, ship_events, chat_suggestion_feeds and chat_suggestions.
  • Rows without a brand: a brandless chat can hold several brands' data, because each tool call picks its brand.
    • Other people's brandless shared chats, files and agent-run chats are visible only to All-brands people (user_has_all_brands()).
    • A person's own brandless rows stay visible to them.
  • A person's own chat about a brand they lose is hidden, not deleted (owner decision).

Coverage test (brand-access-policies.test.js, plus the new brand-access-account-tables.test.js):

  • every top-level OR branch must bind brand_id to brands or the helpers;
  • no union/intersect/except, and no exists on another table's brand_id;
  • brand_id is null only with user_has_all_brands() or a listed own-rows exception;
  • child tables without brand_id must reach a brand or be listed with a reason;
  • no hidden create|alter policy inside $$ bodies;
  • helper callers are to authenticated.
  • Deferred tables: chat_agents, _versions, _triggers (PR 9) and integration_connections (PR 14) sit in a DEFERRED list. A test requires it to be empty once anything writes member_brands or sets brand_scope, which is PR 12.
  • Deliberately broken migrations all failed the test: union, another table's brand_id, an open null branch, intersect, and a web file writing member_brands.

Related issue

None. Brand-level access, PR 3 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 (00390, then 00424, each in one transaction), then brand-access-verify-00390*.sql ran. Every block rolls back.

all manager, before vs after: every count is identical, on 19 tables and functions (brands, chats, messages, files, ships, impacts, deliveries, counters, drafts, inputs, activity, feeds, agent conversations, quota rows and totals). The only change is the invitations count, 1 → 0, as intended.

selected manager (Acme only):

  • the hidden brand's chats, messages, files, why analyses, agent messages, ships, impacts, deliveries, inputs and feed read 0;
  • another person's brandless shared chat and a brandless file read 0, while their own brandless chat reads 1;
  • quotas count the whole Account: locations 43 = Acme 41 + one null row 2, and org_brand_count 2;
  • content_draft_member on the hidden draft → f.

Admin: sees every probe row, and invitations with brand_ids.

Another Account's ids: the three functions return 0 or empty.

service_role: no null row, and content_draft_member → t.

Snapshot/restore on a hidden draft returns null; on Acme it works.

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 (Members' Team list is unchanged)

  • Server: 336 files / 4,650 tests pass.

  • Web: 7,625 of 7,626 pass. The one failure is the clock test fixed in fix(chat): give a chat row the menu's clock, so a run's time matches its day #1876.

  • schema.sql was rebuilt.

For production (@gkhngyk): apply 00390 and then 00424 after 00388/00389, each in one transaction. 00390 sorts before the Chat migrations (--include-all), and 00424 after 00423. No env or cron.

Notes

  • With one hidden brand, the Account total minus the visible brands equals that brand's figure. That number can already be worked out from the totals, and no name or id is shown. This is accepted as part of "Account totals as shares" (spec Q3).
  • A direct Postgres call without a JWT, such as pg_cron, now gets nothing from the three quota functions. No such caller exists today.
  • Next: PR 7 (server assertBrandAccess) and PR 9 (Chat, including recording which brands a chat touched). PR 14 (Google per brand) comes before PR 12.

🤖 Generated with Claude Code

cihan-gyk and others added 4 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]>
…within brand access (00390, 00424)

BRAND-ACCESS PR 3 of 16, on top of 00389. Nothing changes while everyone
has All brands: each rewritten policy is the old one plus the brand
condition, and passes the rows it passed before.

- 00390, the Account's brand tables: prompt_usage_counters,
  content_draft_deliveries and the old Agent's agent_conversations (and
  agent_messages through it) are read only within brand access; the
  organization and person checks stay.
- content_draft_member() asks can_access_brand about the draft's brand,
  so its ten policies (now to authenticated) and three functions follow.
- Plan quotas count the whole Account: org_prompt_location_usage and
  prompt_usage_summary are security definer with a membership or brand
  check; brands the caller can't access come back as one row with no
  brand id. New org_brand_count() for maxBrands, used by createBrand and
  the Brands page (web lib/plan-brand-count.ts, which falls back to the
  old count until the migration is on the database).
- invitations: only admins read them (brand_ids). Settings > Team lists
  the pending ones from the server, without the token or the brands.
- member_brands' check locks the person's profile (for share).
- 00424, Chat's brand tables, after 00400-00422 that create them (in
  00390 a fresh install would fail, and their own policies would win):
  chat_conversations (own, shared, agent run), chat_agent_runs,
  chat_why_analyses, chat_files, chat_activity_log, chat_access_requests,
  ship_events, chat_suggestion_feeds, chat_suggestions. A row with no
  brand stays as it was; an own chat about a hidden brand is hidden, not
  deleted.
- brand-access-policies.test.js: every top-level OR branch ties brand_id
  to brands or the access rule; tables without brand_id reach a brand
  through the row they belong to, or are listed as Account-level with
  why; no policy statement hidden in a $$ body; access-rule policies for
  authenticated only; no policy before its table. Each check was seen to
  fail on deliberately broken temporary migrations, since deleted.
- brand-access-account-tables.test.js: each rewritten policy is its old
  rule plus the brand condition, for authenticated; the functions, the
  invitations policy and the lock.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…people (00390, 00424)

BRAND-ACCESS PR 3 review fixes. Nothing changes while everyone has All
brands.

- 00390 adds user_has_all_brands(): whether the caller is an admin or has
  All brands (stable, security definer, empty search path; authenticated
  and service_role only).
- 00424: a shared chat, an agent run's chat, an agent run and a filed file
  with no brand may hold any brand's data (a chat with no brand lets each
  tool call pick its own), so only All-brands people read someone else's:
  `brand_id in (select public.user_brand_ids()) or (brand_id is null and
  (select public.user_has_all_brands()))`. The person's own rows with no
  brand stay theirs: their own chat, Chat changes, access requests and old
  Agent chats (with the admins').
- 00390's header notes the one change for All-brands people: someone who
  moved organization no longer reads their old organization's branded
  Agent chats (agent_conversations never checked the organization).
- Coverage test: `brand_id is null` binds only with user_has_all_brands()
  in the same branch, or on the listed own-row policies, each with why; a
  subquery with union, intersect or except, and an `exists` tying brands to
  another table's brand_id, no longer bind. chat_agents (and its versions
  and triggers, PR 9) and integration_connections (PR 14) move to a
  DEFERRED list that must be empty once code writes member_brands or
  brand_scope (PR 12). Each new rule was seen to fail on deliberately broken
  temporary files, since deleted.
- plan-brand-count falls back to the old count only when org_brand_count
  is missing (PGRST202, 42883) and throws on any other error.

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.
# Conflicts:
#	web/src/lib/actions/brand.test.ts
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 1fe651e: #1879's fixed branch merged in (createBrand inserts without returning, then reads back by id); no fix of its own. Apply 00388, 00389, 00390 and 00424 before merging.

The rebase onto #1879's fix. this branch changes createBrand so it picks its own id, inserts without returning and reads the row back. This PR changes the brand count in the same function. brand.ts merged cleanly, and both changes are kept: countPlanBrands runs first, then the insert without returning. brand.test.ts had a conflict in the client mock:

  • I kept this PR's rpc mock (org_brand_count) and take-1879's select chain for the read-back.
  • I dropped the old countFilters bookkeeping, since the count no longer goes through from('brands').
  • All 8 tests pass, including "never insert … returning" and "counts every brand of the organization".
  • schema.sql is unchanged after build-schema.sh.

Quotas. createBrand and the Brands page now both count through org_brand_count, so they always agree. A person with Selected brands gets the Account's number, not the brands they can see. The location quota (org_prompt_location_usage, which savePromptSet, getPromptCapacity, the Tracked Prompts KPI and import_prompts use) and prompt_usage_summary also count the whole Account. The fallback in countPlanBrands only kicks in on PGRST202/42883. Any other error throws, so the limit can't pass on a failed count. No other plan limit counts brand rows through RLS: seats, briefs, audits and the rest are counted by the server.

Invitations. Only admins can create, change or read invitations: the RLS policies say so and requireAdmin checks it too. The 00388 checks hold on top of that: an admin invitation is always All brands, brand ids only go with Selected, and every brand must belong to the organization. listInvitations reads through the server with explicit columns, so the Team list looks the same for members. getTeamInfo and inviteMember already counted through the server.

Migrations.

  • 00390 is free.
  • 00424 is in the Chat block, and it only touches Chat's tables, so it fits there. It sorts after 00423, which is open in #1871/#1880/#1882/#1890 and only adds a function, so there's no policy overlap.
  • #1888 and #1891 carry the same four files because they stack on this PR. No other open PR uses 00390 or 00424.
  • Every new function is security definer with search_path = '', and execute is revoked from public/anon.
  • The membership checks inside the functions only match the caller's own profile.
  • Policies call (select public.user_brand_ids()) once per query.
  • Nothing rewrites a table. Each statement is a policy or function swap.

Checks on this branch:

  • It merges cleanly on current main (main is already its ancestor).
  • server vitest: 4650/4650.
  • web vitest: 7626/7627. The one failure is chat-menu.test.tsx, the date-dependent test that #1876 fixes.
  • plan-brand-count, brand, team, prompt-locations, Brands page and plan-row.test.ts all pass.
  • tsc --noEmit passes, and prettier and eslint are clean on every touched file.

Deploy order: apply 00388, 00389, 00390 and 00424, each in its own transaction, then deploy the web. The web works before 00390 too, through the countPlanBrands fallback.

@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 e57eaca into ansvisor:main Oct 31, 2026
3 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