Skip to content

feat(db): check brand access in the citation and report functions (brand access PR 4, 00426) - #1891

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

gkhngyk merged 7 commits into
ansvisor:mainfrom
cihan-gyk:feature/brand-access-rpc-1

Conversation

@cihan-gyk

@cihan-gyk cihan-gyk commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

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 for public.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 replace of the latest definition of each function:

  • The functions:
    • citations_window_stats
    • citation_url_candidates
    • citation_url_occurrences
    • citations_domains
    • citations_urls
    • citation_gap_domains
    • citation_competitor_sources
    • citations_urls_daily (latest in 00119)
    • citation_gap_domains_daily
    • citation_competitor_sources_daily
    • report_citation_evidence
  • Only the guard line changes:
    • in the 8 SQL functions, the allowed CTE is select 1 where public.can_access_brand(p_brand_id), evaluated once;
    • in the 3 plpgsql ones, if not public.can_access_brand(p_brand_id) then return;.
  • These stay the same: signature, return type, language, stable, security definer, search_path, work_mem (96 MB / 64 MB) and plan_cache_mode. Grants are kept too (create or replace keeps them; 00426 has no grant or revoke).
  • The functions' comments now say brand access (can_access_brand, 00426) instead of "members of the brand's organization". citations_urls_daily and report_citation_evidence, which had none, get one.
  • None of the eleven has a service-role bypass, so the service role reads nothing, as before.
  • schema.sql is rebuilt. Types are unchanged.

Guard test (web/src/lib/brand-access-functions.test.ts) reads schema.sql and tracks each function's latest definition, alter function … security, drops and authenticated grants:

  • Every callable SECURITY DEFINER function that takes p_brand_id, or reads organization_id against auth.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, and org_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.sql was 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:

  • the settings table's checks_brand / checks_organization columns;
  • the Selected-brands manager's rows for the brand they weren't given, which now read empty. Before 00426 they read the same as the Admin; that is the leak closing.

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:

  • PR 5 (12): insights, mentions and topics: 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.
  • PR 6 (20 + 3): AI traffic (7), content (9) and shopping/catalog (4), plus the role-guarded seed_kpi_presets, override_mention_sentiment and approve_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 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

  1. Apply 00426 after 00388–00390 and 00424 (feat(db): add per-brand access for people: brand scope, member brands and access helpers (00388) #1878, feat(db): read, change and delete a brand only within the person's brand access (00389) #1879, feat(db): keep the Account-wide brand tables, quotas and invitations within brand access (00390, 00424) #1881).
  2. Run the verify file before and after, and diff the outputs. Only the rows above change.
  3. Run yarn vitest run src/lib/brand-access-functions.test.ts.

Checklist

  • Branch follows the naming convention
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/)
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR
  • Help article updated under help/ (or no user-visible change)

On this commit: format:check and typecheck pass, lint has 0 errors (7 old warnings), and the brand-access tests pass (30 tests in 5 files).

Mutation checks. These fail the test:

  • a changed work_mem;
  • a new org-guarded p_brand_id function;
  • an org check through brands without p_brand_id;
  • a stale list entry;
  • the old guard put back by a later migration;
  • a variable brand_scope write.

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-all only if applied out of order.

PR 12 note: server/src/lib/health/report.js calls 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 and lib/head-to-head.ts calls it. Dev drift only, not from this PR.

🤖 Generated with Claude Code

cihan-gyk and others added 6 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]>
…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]>
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 31, 2026
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.

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_mem and plan_cache_mode are repeated as they were. No later alter function touches any of them.
  • can_access_brand is security definer with search_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_daily and citations_window_stats_daily. They're security invoker over rollup tables whose policies read brands under 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.sql rebuilds 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 and guards/plan-row.test.ts all pass.
  • The server tests brand-access-* and demo/* pass.
  • tsc --noEmit is clean, and prettier and eslint are clean on the changed files.

Order: 00388 → 00389 → 00390 → 00424 → 00426, after #1878, #1879 and #1881.

@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 36c11f6 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