Repository navigation
feat(db): check brand access in the citation and report functions (brand access PR 4, 00426) - #1891
Merged
Merged
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]>
…426) The eleven security definer functions behind Citations and the report's citation evidence asked only whether the brand belongs to the caller's organization, so a Selected-brands person could read any brand's citations through them. Each now asks can_access_brand(p_brand_id) (00388): citations_window_stats, citation_url_candidates, citation_url_occurrences, citations_domains, citations_urls, citation_gap_domains, citation_competitor_sources, citations_urls_daily, citation_gap_domains_daily, citation_competitor_sources_daily and report_citation_evidence. Each is its last definition word for word with only the check changed: arguments, result, language, volatility, security definer and settings (search_path, work_mem, plan_cache_mode) are repeated; grants and comments are kept by create or replace. Nothing changes while everyone has All brands; anon and the service role still read nothing. web/src/lib/brand-access-functions.test.ts reads schema.sql: every security definer function a signed-in person can call that takes p_brand_id (or joins brands to the caller's profile) checks brand access or is listed for BRAND-ACCESS PR 5/6, and the 00426 functions keep the rest of their definitions unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…en the function check (00426) 00426's comments: the eleven functions' comments said "members of the brand's organization" or "an organization check"; they now say brand access (can_access_brand). citations_urls_daily and report_citation_evidence, which had none, get one. web/src/lib/brand-access-functions.test.ts: - Finds 00426's definition by migration and compares it with the one it replaced, so a later migration that redefines these functions keeps CI green; the last definition must still ask can_access_brand(p_brand_id). - Catches every callable security definer function that looks at the caller's organization (auth.uid() and organization_id) without an access helper, not only the brands-to-profile join: approve_action_task_review, override_mention_sentiment and seed_kpi_presets are found without being named. Those that need no brand check (the helpers, org_brand_count) are listed with why. - Counts every brand_scope write as narrowing, whatever its value. - Only grants and revokes are forbidden in 00426; each function's comment there must name can_access_brand. Co-Authored-By: Claude Opus 5.5 <[email protected]>
8 of 13 tasks
gkhngyk
previously approved these changes
Oct 31, 2026
gkhngyk
left a comment
Contributor
There was a problem hiding this comment.
Approving. 00426 does what it says, and with everyone on All brands nothing changes.
Checked
- Each function against its last definition (00063, 00069, 00111, 00119, 00203), diffed text against text. All eleven are the earlier body word for word; only the guard changes:
- in the 8
allowed-CTE functions,select 1 where public.can_access_brand(p_brand_id); - in the 3 plpgsql ones,
if not public.can_access_brand(p_brand_id) then return;. - Headers,
search_path,work_memandplan_cache_modeare repeated as they were. No lateralter functiontouches any of them.
- in the 8
can_access_brandis security definer withsearch_path = ''. Its rule matches the old check exactly for an Admin or All-brands person: organization membership. The guard runs once per call, not per row.- Callers. All the web callers (
actions/citations.ts,actions/reports.ts) use the signed-in person's client, so the check sees the acting person. No server code calls these with the service role. The health probe uses a probe person's session; your PR 12 note about that person needing access is right. - Not in this wave, and fine:
citations_domains_dailyandcitations_window_stats_daily. They're security invoker over rollup tables whose policies readbrandsunder RLS, so they follow 00389 on their own. - Migration numbers: 00426 is unique across main and the open PRs, and no other open PR redefines any of these functions.
- Merge: the branch is up to date with main, and with #1881's current head merged in there are no conflicts.
schema.sqlrebuilds identically.
Tests on the PR merged with #1881's head (main is already in):
brand-access-functions.test.ts,plan-brand-count,prompt-locations,brand,team, the brands page andguards/plan-row.test.tsall pass.- The server tests
brand-access-*anddemo/*pass. tsc --noEmitis clean, and prettier and eslint are clean on the changed files.
Order: 00388 → 00389 → 00390 → 00424 → 00426, after #1878, #1879 and #1881.
gkhngyk
approved these changes
Oct 31, 2026
gkhngyk
left a comment
Contributor
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.
8 of 13 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Brand-level access, PR 4 of ~16: RPC wave a, the citation and report functions. Migration 00426. Stacked on #1881 (→ #1879 → #1878). Nothing changes while everyone is All brands.
Why: these eleven functions are SECURITY DEFINER and callable by
authenticated, so they bypass RLS. Their guard checked only the organization:exists (… brands b join profiles pf on pf.organization_id = b.organization_id where b.id = p_brand_id and pf.id = auth.uid()). A Selected-brands person could therefore read a brand they weren't given through Citations. 00426 swaps that guard forpublic.can_access_brand(p_brand_id)(00388). It passes when the brand is in the person's Account and they are an Admin, All brands, given the brand, or the brand is the demo brand.00426:
create or replaceof the latest definition of each function:citations_window_statscitation_url_candidatescitation_url_occurrencescitations_domainscitations_urlscitation_gap_domainscitation_competitor_sourcescitations_urls_daily(latest in 00119)citation_gap_domains_dailycitation_competitor_sources_dailyreport_citation_evidenceallowedCTE isselect 1 where public.can_access_brand(p_brand_id), evaluated once;if not public.can_access_brand(p_brand_id) then return;.language,stable,security definer,search_path,work_mem(96 MB / 64 MB) andplan_cache_mode. Grants are kept too (create or replacekeeps them; 00426 has no grant or revoke).can_access_brand, 00426) instead of "members of the brand's organization".citations_urls_dailyandreport_citation_evidence, which had none, get one.schema.sqlis rebuilt. Types are unchanged.Guard test (
web/src/lib/brand-access-functions.test.ts) readsschema.sqland tracks each function's latest definition,alter function … security, drops andauthenticatedgrants:Every callable SECURITY DEFINER function that takes
p_brand_id, or readsorganization_idagainstauth.uid(), must call a brand-access helper (can_access_brand,user_brand_ids,user_has_all_brands,content_draft_member) or be on a list:TO_CONVERT(PRs 5–6);NO_BRAND_CHECK, with its reason: the helpers themselves, andorg_brand_count's Account total (§9 Q3).Converting one without taking it off its list fails.
Compared with the definition before 00426, the wave's functions keep their header, and their body word for word apart from the guard. A later migration that redefines one (say for
work_mem) doesn't break this, as long as it keeps the brand check.00426 has no grant or revoke, and each wave function's comment names
can_access_brand.Before PR 12 lets anyone be Selected brands, the list must be empty.
The parser's "callable SECURITY DEFINER" list matches the dev database's
has_function_privilege.Dev database: applied.
~/.claude/ansvisor-tools/brand-access-verify-00426.sqlwas run before and after: one transaction, rolled back, with probe people. It calls the eleven functions as seven personas on two brands. The diff is exactly the expected one:checks_brand/checks_organizationcolumns;The demo Admin, an All-brands Manager, another Account's person, another Account's brand, anon and the service role read identical row counts and md5s before and after.
Left for PRs 5–6:
head_to_head_daily,insights_change_drivers(_daily),insights_same_prompt_compare(_daily),insights_topic_competitors_daily,mentions_list,mentions_overview,mentions_perception,prompt_position_summaries_json,prompt_visibility_summaries,topics_overview_window.seed_kpi_presets,override_mention_sentimentandapprove_action_task_review. Most of these skip the check for the service role; that skip stays.Related issue
None. Brand-level access (spec
BRAND-ACCESS), PR 4.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
yarn vitest run src/lib/brand-access-functions.test.ts.Checklist
yarn lintpasses (run fromweb/)yarn typecheckpasses (run fromweb/)yarn format:checkpasses (run fromweb/)help/(or no user-visible change)On this commit:
format:checkandtypecheckpass,linthas 0 errors (7 old warnings), and the brand-access tests pass (30 tests in 5 files).Mutation checks. These fail the test:
work_mem;p_brand_idfunction;brandswithoutp_brand_id;brand_scopewrite.A later
work_mem-only redefinition doesn't.Review: the pre-push review found no blocker. Its shoulds are fixed in a3d09f8: the test broke on a later, legitimate redefinition, and its org-check pattern was too narrow. The stale comments are fixed there too. Re-applied on dev, the verify diff shows the comment columns only.
Prod order: 00388 → 00389 → 00390 → 00424 → 00426. 00426 sorts after 00425 (#1883), so it needs
--include-allonly if applied out of order.PR 12 note:
server/src/lib/health/report.jscalls the health probe user "a member of that brand's organization". Once Selected brands exist, that person must be an Admin, All brands, or given the brand. Otherwise the probe reads empty and looks fast.Found on the way: the dev database has no
head_to_head_daily(00169) even though main has it andlib/head-to-head.tscalls it. Dev drift only, not from this PR.🤖 Generated with Claude Code