Files
khb_microservices/packages/khb_common/migrations/021_agent_read_roles.sql
2026-10-21 11:50:22 +03:00

48 lines
4.0 KiB
SQL
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

-- Настройки самих ролей (default_transaction_read_only = on, statement_timeout = '20s', connection limit) и usage на схему задаёт администратор БД
-- при создании роли: у khb_app нет прав менять чужие роли.
-- Чтение зеркала Supabase консольными агентами (khb-sql). Роли создаются отдельно администратором БД (create role ... login password ...),
-- поэтому миграция выполняется только для существующих ролей. Только select, по белому списку; запись и другие объекты недоступны.
-- khb_agent - агенты менеджеров: зеркало JobTread, календарь, проекты и менеджеры, люди (без почты)
-- khb_agent_ceo - агент руководителя: то же и отчёты (Employee Activity, To-do): события JobTread, активность, сообщения проектных каналов,
-- журнал сообщений, представления активности и задач менеджера, процесс to-be, напоминания, списки задач на день
do $$
declare
t text;
base_tables text[] := array['jt_job','jt_membership','jt_task_type','jt_task','jt_task_dependency','jt_task_assignment',
'jt_job_hist','jt_membership_hist','jt_task_type_hist','jt_task_hist','jt_task_dependency_hist','jt_task_assignment_hist',
'calendar_day','assistant_project'];
ceo_tables text[] := array['jt_event','activity_sync_state','activity_tracked_person','slack_channel_message','slack_message_log','project_channel',
'reminder_history','manager_day_list','khbuild_process','khbuild_roles','khbuild_systems','khbuild_data_objects'];
ceo_views text[] := array['v_activity_action','v_manager_task_list'];
r text;
begin
foreach r in array array['khb_agent','khb_agent_ceo'] loop
if not exists (select 1 from pg_roles where rolname = r) then continue; end if;
begin
foreach t in array base_tables || case when r = 'khb_agent_ceo' then ceo_tables else array[]::text[] end loop
if to_regclass('public.' || t) is null then continue; end if;
execute format('grant select on %I to %I', t, r);
-- политики бывают только у таблиц; для представлений достаточно grant
if exists (select 1 from pg_class where oid = to_regclass('public.' || t) and relkind in ('r', 'p')) then
execute format('drop policy if exists %I on %I', r || '_read', t);
execute format('create policy %I on %I for select to %I using (true)', r || '_read', t, r);
end if;
end loop;
if r = 'khb_agent_ceo' then
foreach t in array ceo_views loop
if to_regclass('public.' || t) is not null then execute format('grant select on %I to %I', t, r); end if;
end loop;
end if;
-- люди и менеджеры: только безопасные колонки (без почты и дополнительных адресов)
execute format('grant select (id, display_name, jt_membership_id, slack_user_id, is_active) on person to %I', r);
execute format('drop policy if exists %I on person', r || '_read');
execute format('create policy %I on person for select to %I using (true)', r || '_read', r);
execute format('grant select (person_id, is_active, slack_channel_id, chat_kind) on construction_manager to %I', r);
execute format('drop policy if exists %I on construction_manager', r || '_read');
execute format('create policy %I on construction_manager for select to %I using (true)', r || '_read', r);
exception when insufficient_privilege then
raise notice 'нет прав выдать чтение роли % (выдать вручную администратором БД)', r;
end;
end loop;
end $$;