Repository navigation
feat(db): keep the Account-wide brand tables, quotas and invitations within brand access (00390, 00424) - #1881
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]>
…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
left a comment
There was a problem hiding this comment.
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
rpcmock (org_brand_count) and take-1879'sselectchain for the read-back. - I dropped the old
countFiltersbookkeeping, since the count no longer goes throughfrom('brands'). - All 8 tests pass, including "never insert … returning" and "counts every brand of the organization".
schema.sqlis unchanged afterbuild-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 definerwithsearch_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 andplan-row.test.tsall pass.tsc --noEmitpasses, 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
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 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_deliveriesandagent_conversations(andagent_messagesthrough it) addbrand_id in (select public.user_brand_ids()),to authenticated.content_draft_member()checkscan_access_brand(d.brand_id). The 10 policies that use it areto authenticated.org_prompt_location_usagebecomes membership-checked SECURITY DEFINER. Brands the caller can't see are summed into onebrand_id = nullrow, so totals stay whole and no hidden brand is named.prompt_usage_summarybecomes SECURITY DEFINER and checks brand access.org_brand_count()formaxBrands.lib/plan-brand-count.ts, used bycreateBrandand the Brands page. It falls back to the old count only onPGRST202/42883(deploy order).team.tslistInvitationsreads through the server with explicit columns (no token, nobrand_ids), so Members still see the same Team list.user_has_all_brands(): true for Admins andall, STABLE, SECURITY DEFINER,search_path = ''.member_brandscheck trigger locks the profile row (for share).00424 (Chat):
chat_conversations(own, shared, agent run),chat_agent_runs,chat_why_analyses,chat_files,chat_activity_log,chat_access_requests,ship_events,chat_suggestion_feedsandchat_suggestions.user_has_all_brands()).Coverage test (
brand-access-policies.test.js, plus the newbrand-access-account-tables.test.js):brand_idtobrandsor the helpers;union/intersect/except, and noexistson another table'sbrand_id;brand_id is nullonly withuser_has_all_brands()or a listed own-rows exception;brand_idmust reach a brand or be listed with a reason;create|alter policyinside$$bodies;to authenticated.chat_agents,_versions,_triggers(PR 9) andintegration_connections(PR 14) sit in aDEFERREDlist. A test requires it to be empty once anything writesmember_brandsor setsbrand_scope, which is PR 12.brand_id, an open null branch, intersect, and a web file writingmember_brands.Related issue
None. Brand-level access, PR 3 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 (00390, then 00424, each in one transaction), then
brand-access-verify-00390*.sqlran. Every block rolls back.allmanager, 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.selectedmanager (Acme only):org_brand_count2;content_draft_memberon 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 lintpasses (0 errors; 7 old warnings in files this PR doesn't touch)yarn typecheckpassesyarn format:checkpassesChanges 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.sqlwas 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
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