Repository navigation
feat(server): check a person's brand access, not only their organization (brand access PR 7) - #1888
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]>
…ion (brand access PR 7) assertBrandAccess follows the database's can_access_brand (00388): within the organization, All brands reaches every brand, Selected brands only the ones granted (member_brands), an Admin and the demo brand always. Another organization's brand stays 403 not_in_workspace; one not granted is 403 no_brand_access. The caller's organization, role and scope are read once per /api request (lib/request-scope.js). The opportunity and prompt checks follow it, the six hand-written copies in prompts, tracking and content use it, and the Google property lists take ?brandId= (without one they need All brands). Everyone has All brands today, so nothing changes yet. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ore 00388, and end the request cache with the response (brand access PR 7) - The prompt suggestion and Improve routes, the Google integration routes and Action Center's catches pass the refusal's code on (not_in_workspace, no_brand_access, forbidden): their 403 used to be the bare "Unauthorized" the web read as another workspace's brand (BUG-001). Catalog keeps an access refusal's own code instead of calling it a role's. The web reads no_brand_access as 'workspace' too: switch to one of your brands. - Before 00388 there is no profiles.brand_scope: on 42703 or PGRST204 the profile is read without it, everyone counts as All brands, and that is logged once (the code and the migration, no person). - The request's store closes when its response finishes or its connection closes, so a job the request leaves running reads afresh from then on. - The Google property lists always need All brands until each brand has its own connection (PR 14): the list is the whole organization's, and naming the demo brand opened it. A sync of every brand needs All brands too. - A failed brand read is a failure (500), not "Brand not found"; an id that isn't a uuid stays 404. A caller without an organization reaches no brand (403 not_in_workspace), so /:id/brief's own check for one goes. Grants are read within the person's organization. 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
Co-Authored-By: Claude Opus 5.5 <[email protected]>
- PUT /api/audits/settings: the auto-audit switch and the e-mail after a run are the organization's, for every brand, so changing them needs All brands. A brand's own exclude patterns still only need that brand. The refusal keeps its code. - GET /api/billing/ai-usage/draft/:draftId: a page's share of the AI budget is read only by someone who reaches the page's brand. - The MCP key's mark-published path: the key's user must reach the draft's brand; a brand they weren't given reads as not there.
gkhngyk
left a comment
There was a problem hiding this comment.
Approving, with three small fixes on top: branch take-1888, commit a2f431fb8f8575071bc4e5962e12fcd359306c01. It's a fast-forward of this PR's head. It has #1881's current head (1fe651e2, which brings #1879's createBrand fix) merged in, and then one fix commit.
The rebase onto #1881 / #1879. The merge was clean. brand.ts keeps countPlanBrands first and then the insert without returning. 00389 and schema.sql are now #1879's fixed versions. build-schema.sh leaves schema.sql unchanged. Current main (703a6860) is already an ancestor, so the branch merges clean on main.
The helper. assertBrandAccess follows can_access_brand's rule:
- same Account;
- then Admin, All brands, the demo brand, or a grant.
brand_scope is not null and limited to all/selected, so !== 'selected' and the SQL's = 'all' always agree. The refusals give 404 for an unknown brand, 403 not_in_workspace and 403 no_brand_access, the same split main already made. A failed read is a 500, never a 403.
The request cache. The profile and grants are read once per request. In the worst case a request reads the brand row once per brand it checks, plus one profile read and one grant read. A failed read is not kept. Once the response finishes or closes, work the request left running reads fresh. The tests cover both finish and close.
The last two commits.
- Refusal codes: the codes now reach the web on the prompt, Improve, integrations, Action Center and catalog paths, and
api-failure.tsreadsno_brand_accessas'workspace'. - Pre-00388 fallback: it only kicks in on
42703/PGRST204. Any other error throws. - GSC/GA property lists: they need All brands now. The whole-Account syncs need it too.
- Format commit: formatting only.
I went through every handler in server/src/routes. Every one that takes a brand id goes through assertBrandAccess or a wrapper: brandFor, assertWriter, assertWebhookEditor, assertOpportunit(y|ies)Access, assertPromptAccess. Child ids are kept to the checked brand: drafts, audits, prompts, suggestions, sources, facts, connections, signals, tasks and jobs. That's either .eq('brand_id', …) or the brand is read from the row itself. The tracking worker keeps promptId to the brand's prompt sets.
Fixes in a2f431fb (each with a test that fails without it):
PUT /api/audits/settings. The auto-audit switch and the e-mail after a run are stored per Account and apply to every brand. Changing them now needs All brands. A brand's exclude patterns still only need that brand. The settings dialog only sends what changed, so a Selected-brands Manager can still save patterns.sendAuditErrornow passes the refusal'scodeon.GET /api/billing/ai-usage/draft/:draftId. It now reads the draft's brand and checks access before reading the page's share. A draft id that isn't found answers as before.- The MCP key's mark-published path (
publishDraftForKeyUser). The key's user must reach the draft's brand. A refusal reads as "Draft not found", as another Account's draft does. A failed read still throws.
Left for later, non-blocking while everyone is All brands. These fit the later PRs listed in the description:
- PR 14 (Google per brand): the catalog's sign-in account list (
GET /catalog/accounts) andPOST /catalog/sourcesfor sign-in kinds use the Account's sign-in, just like the GSC/GA property lists.POST /:provider/connectandDELETE /:providerare Account-wide. - PR 10 (MCP): the internal brief, site-audit and recount endpoints take no user, so the brand check there belongs in the MCP layer.
- Small:
POST /prompts/suggestions/:id/acceptand/topics/suggestions/:id/acceptstore thepromptId/topicIdthey're given without tying it to the brand. Nothing reads those columns through a join today. - Performance:
assertRole,canChangeSettingsand the catalog/CMSassertWriterread the profile again rather than taking the rolebrandAccessOfalready has. That's one extra query per request.
Checks on take-1888:
- Server: full suite 4,691 passed, 3 skipped. The only failures under load are the known timing tests in
content-agent/content-people, and they pass alone.eslint srcis clean, and prettier is clean on every touched file. - Web:
api-failure,brandandplan-row.test.tspass (28 tests),tsc --noEmitpasses, and eslint/prettier are clean on the touched files. - Migrations: none in this PR. 00388–00390 and 00424 come from the stack.
Deploy order: apply 00388–00390 and 00424, then deploy this server. The fallback keeps everyone on All brands until 00388 is applied.
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 7 of ~16: the server checks a person's brand access, not only their organization. Stacked on #1881 (→ #1879 → #1878). No migration. Nothing changes while everyone is All brands.
server/src/lib/access.jsbrandAccessOf(userId)reads the profile once (organization_id,role,brand_scope), plusmember_brands(filtered by the organization) for a Selected-brands person.can_access_brand's (00388): same Account, and Admin, All brands, the demo brand, or a granted brand.assertBrandAccess(brandId, userId, { columns })returns{ brand, orgId, role }. Refusals:not_in_workspace;no_brand_access;assertAllBrands(userId)is for Account-wide lists.assertOpportunitiesAccessandassertPromptAccessfollow the same rule.not_in_workspace, as before.One read per request:
server/src/lib/request-scope.js(AsyncLocalStorage) sits at the head of the/apichain.Copies brought onto the helper:
prompts.js's ownassertBrandAccessis gone. Improve gets its brand fields through{ columns }.tracking.jsroutes its three inline checks throughbrandFor().content.js/generateand/:id/briefuse the helper.code(prompts' suggestions and Improve, action-center, integrations), andcatalog.jspasses the code through. Inweb/src/lib/api-failure.ts,not_in_workspaceandno_brand_accessboth read as'workspace', so the "this brand isn't in your workspace" toast shows as before (BUG-001).Integrations: the GSC/GA property lists and the brandless sync endpoints call
assertAllBrands. They return the whole Account's Google properties, so they stay All brands until PR 14 moves Google per brand. The single-brand sync (brandId) is open to a brand the person has.Behaviour while everyone is All brands:
Related issue
None. Brand-level access (spec
BRAND-ACCESS), PR 7.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
Run
cd server && npx vitest run src/lib/access.test.js src/lib/request-scope.test.js src/routes.access.testcovers:Route tests cover prompts' suggestions (403 + code, nothing written), tracking (403/404/500 bodies), content
/generateand/:id/brief, integrations properties and sync, and action-center deletes.With 00388–00390 applied, set a test person to
brand_scope = 'selected'with onemember_brandsrow. Their other brands answer 403no_brand_access; the granted one and the demo brand work.Checklist
yarn lintpasses (run fromweb/)yarn typecheckpasses (run fromweb/)yarn format:checkpasses (run fromweb/)help/(or no user-visible change)Server:
npm run format(own files only),npm run lintand the full suite pass (4,688 tests, 3 skipped). Web:api-failure.tsand its test pass format, lint, typecheck and tests (18).Deploy order: 00388 before this server, though the fallback above keeps everyone All brands until it is applied.
Review: the pre-push review found no blocker. Its shoulds are fixed in f6f3a53:
Its smaller items are fixed too.
Left for later PRs
brandInOrgchecks (27 call sites).GET /api/billing/ai-usage/draft/:draftIdchecks only the organization;content.jscatches (e.g./:id/action) still drop the code;assertOpportunitiesAccess/assertPromptAccessstill turn a read error into a 403.🤖 Generated with Claude Code