К основному содержанию
скилл CX Codex

database-security — скилл для Claude Code: аудит RLS и доступов к БД

Скилл database-security проверяет доступ к данным в Supabase, Postgres и Convex: покрытие RLS, дыры в политиках, аудит-логи. Пригодится перед релизом или при разборе инцидента.

MIT 208 установок ★ 29 обновлён 2026-08-17

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add oakoss/agent-skills --skill database-security -a claude-code
Открыть на GitHub

Что делает database-security

Скилл проводит аудит слоя данных: перебирает точки входа в базу, проверяет, что на каждой публичной таблице включён RLS, читает политики на логические обходы и ищет ключ service_role в клиентском коде. Дальше идут функции с security definer, вьюхи без security_invoker, конфигурация PGAudit и JIT-доступы. Порядок шагов фиксированный: от картирования поверхности атаки до сверки с требованиями комплаенса.

Внутри — справочные таблицы, а не скрипты. Быстрые рецепты: индексировать колонки из RLS-выражений, оборачивать auth.uid() в подзапрос, разбивать FOR ALL на отдельные политики по операциям. Рядом список антипаттернов с правильной заменой. Для Convex своя проверка: вызов ctx.auth.getUserIdentity() в каждой публичной функции.

Слэш-командой скилл не вызывается, агент подхватывает его сам, когда разговор заходит о доступах к базе. За OWASP Top 10 и заголовки безопасности отвечает соседний скилл про безопасность приложения. Колонки из выражений USING требуют индексов: без них RLS заметно тормозит запросы в продакшене.

Какие задачи решает

  • проверить, что RLS включён на всех публичных таблицах
  • найти ключ service_role, попавший в клиентский код
  • разбить политику FOR ALL на отдельные операции
  • настроить аудит-лог изменений через триггеры или PGAudit
  • закрыть вьюхи через security_invoker = true

Примеры запросов агенту

  • Проверь доступ к таблице orders: включён ли RLS и что разрешает политика на SELECT.
  • Найди в клиентском коде использование service_role и скажи, куда его перенести.
  • Настрой аудит-лог изменений в таблице users через триггер.

Как установить database-security

1Через Skills CLI (Vercel)

npx skills add oakoss/agent-skills --skill database-security -a claude-code

2Вручную: положить файлы

~/.claude/skills/database-security/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/database-security/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о database-security

Как установить database-security в Claude Code?

Выполните npx skills add oakoss/agent-skills --skill database-security -a claude-code. Файл скилла появится по пути ~/.claude/skills/database-security/SKILL.md.

Что делает database-security?

Прогоняет аудит безопасности базы по фиксированной последовательности: поверхность атаки, покрытие RLS, разбор политик, утечки service_role, функции и вьюхи, аудит-логи, сверка с требованиями комплаенса.

Чем он отличается от скилла про безопасность приложения?

Этот работает на уровне данных: RLS в Supabase и Postgres, auth-гарды в Convex, PGAudit, JIT-доступы. OWASP Top 10, валидация ввода и заголовки безопасности остаются за соседним скиллом.

Исходный текст

SKILL.md · MIT
---
name: database-security
description: 'Database security auditor specialized in Row Level Security (RLS) enforcement, Zero-Trust database architecture, and forensic audit trails. Covers Supabase RLS policies, Postgres security, Convex auth guards, PGAudit configuration, JIT access controls, and database-specific compliance validation. Use when auditing database access policies, implementing RLS in Supabase or Postgres, configuring Convex auth guards, setting up audit logging, reviewing database security, or validating database-level compliance requirements.'
license: MIT
metadata:
  author: oakoss
  version: '1.0'
user-invocable: false
---

# Security Audit

Database security auditor specialized in Row Level Security (RLS) enforcement, Zero-Trust database architecture, and forensic audit trails. Focuses on Supabase, Postgres, and Convex data layer security. For general application security (OWASP Top 10, auth patterns, security headers, input validation), use the `security` skill instead.

## Quick Reference

| Need                 | Approach                                                       |
| -------------------- | -------------------------------------------------------------- |
| RLS enforcement      | Enable on every public table; separate policies per operation  |
| RLS performance      | Index RLS columns; wrap auth.uid() in (select ...) subselect   |
| Zero-Trust DB        | Micro-segmentation, identity propagation, TLS enforcement      |
| Supabase auth in RLS | Use (select auth.uid()) and auth.jwt(); never auth.role()      |
| Convex auth guards   | Call ctx.auth.getUserIdentity() in every public function       |
| JIT access           | Time-bound grants that expire automatically                    |
| Audit trails         | Database triggers with immutable audit_log table               |
| PGAudit              | Extension for statement-level and object-level SQL auditing    |
| Service role safety  | Never use service_role key in client-side code                 |
| Views and RLS        | Use security_invoker = true (Postgres 15+) to enforce RLS      |
| Schema segmentation  | Separate public, private, and audit schemas                    |
| Database compliance  | RLS + audit logging + encryption satisfies multiple frameworks |

## Audit Protocol

Follow this sequence when performing a database security audit:

1. **Attack Surface Mapping**: Identify all entry points to the data layer (public APIs, internal dashboards, AI agents, cron jobs)
2. **RLS Coverage Check**: Query pg_tables to verify every public schema table has RLS enabled and appropriate policies
3. **Policy Review**: Check for logical bypasses, missing WITH CHECK clauses, overly permissive FOR ALL policies
4. **Service Role Audit**: Search client code for service_role key exposure; verify it only appears in server-side code
5. **Function Audit**: Check for security definer functions in exposed schemas and Convex functions missing auth guards
6. **Access Simulation**: Execute queries as anon and authenticated roles to verify enforcement
7. **View Audit**: Verify views use security_invoker = true or are not in exposed schemas
8. **Audit Trail Verification**: Confirm triggers or PGAudit capture all security-relevant operations
9. **Compliance Validation**: Map database controls against applicable regulatory frameworks

## Security Principles

| Principle         | Database Application                                   |
| ----------------- | ------------------------------------------------------ |
| Defense in Depth  | RLS + application checks + schema segmentation         |
| Least Privilege   | Minimal GRANT per role; anon gets near-zero access     |
| Zero Trust        | Verify identity at DB level even for internal requests |
| Secure by Default | RLS enabled on creation; default-deny when no policy   |
| Fail Securely     | Postgres default-deny on RLS; generic error responses  |
| Assume Breach     | Design assuming attacker has a valid JWT               |

## Anti-Patterns

| Anti-Pattern                                | Risk                                       |
| ------------------------------------------- | ------------------------------------------ |
| Security by obscurity (UUIDs only)          | Attackers enumerate IDs via IDOR           |
| Anon role with SELECT on sensitive tables   | Public data exposure via Supabase API      |
| RLS columns without indexes                 | Production performance degradation (100x+) |
| Frontend-only permission checks             | Attackers bypass via direct API calls      |
| Standing admin privileges                   | Excessive blast radius if compromised      |
| service_role key in client-side code        | Bypasses all RLS policies completely       |
| FOR ALL policies instead of per-operation   | Unintended write access through broad rule |
| Security definer functions in public schema | Functions callable from API, bypass RLS    |
| Views without security_invoker              | Views bypass RLS silently                  |

## Common Mistakes

| Mistake                                                     | Correct Pattern                                                                |
| ----------------------------------------------------------- | ------------------------------------------------------------------------------ |
| Using auth.uid() = user_id without wrapping in (select ...) | Use (select auth.uid()) = user_id so Postgres caches the result via initPlan   |
| Using FOR ALL instead of separate per-operation policies    | Create separate SELECT, INSERT, UPDATE, DELETE policies for clarity and safety |
| Leaving anon role with SELECT on sensitive tables           | Restrict anon access; require authenticated role for sensitive data            |
| Relying on UUIDs as the only access control                 | Enforce RLS policies and explicit auth checks alongside unique identifiers     |
| No index on columns used in RLS USING clauses               | Add B-tree indexes on all columns referenced in RLS policy expressions         |
| Convex function missing ctx.auth.getUserIdentity() call     | Every public query and mutation must validate identity before accessing data   |
| Using service_role key in client-side code                  | Use anon key client-side; service_role only in server-side functions           |
| Views bypassing RLS without security_invoker                | Set security_invoker = true on views in Postgres 15+                           |
| Security definer functions in exposed schemas               | Place security definer functions in non-exposed schemas with search_path = ''  |
| No audit logging for security-relevant database events      | Use triggers and PGAudit to capture all data access and modifications          |

## Relationship to Security Skill

The `application-security` skill covers general application security: OWASP Top 10, authentication patterns, input validation, security headers, and compliance overviews. This `database-security` skill complements it by focusing on database-layer concerns: RLS policy design and performance, Supabase/Postgres-specific patterns, Convex auth guards, PGAudit configuration, and database-specific compliance implementations (SQL functions for GDPR erasure, HIPAA PHI audit triggers, etc.).

## Delegation

- **Verify RLS enforcement with access simulations**: Use `Task` agent to run anonymous and authenticated queries against every public table
- **Audit Convex functions for missing auth guards**: Use `Explore` agent to scan all query and mutation handlers for getUserIdentity calls
- **Design zero-trust database architecture**: Use `Plan` agent to map schemas, access policies, JIT grants, and audit log design
- **Generate database compliance evidence**: Use `Task` agent to run audit queries and produce compliance reports

## References

- [rls-performance.md](references/rls-performance.md) -- RLS policy performance, initPlan caching, stable functions, separate policies, EXPLAIN benchmarking
- [zero-trust-database.md](references/zero-trust-database.md) -- Micro-segmentation, identity propagation, connection security, JIT access controls
- [audit-logging.md](references/audit-logging.md) -- Trigger-based auditing, PGAudit extension and log classes, log integrity, tamper-proof storage
- [convex-security.md](references/convex-security.md) -- Identity validation, manual RLS in functions, granular functions, role-based access via JWT claims
- [threat-modeling.md](references/threat-modeling.md) -- STRIDE applied to database access, RLS bypass vectors, data layer trust boundaries
- [application-security.md](references/application-security.md) -- Service role management, schema exposure, security definer functions, views and RLS
- [compliance-frameworks.md](references/compliance-frameworks.md) -- Database-specific GDPR, HIPAA, SOC2, PCI-DSS requirements and SQL implementations

© oakoss · MIT · oakoss/agent-skills

Похожие скиллы

Все скиллы по теме «Безопасность» →
supabase-security-audit davila7 Команда supabase-security-audit для Claude Code проводит аудит безопасности Supabase: проверяет RLS-политики, права доступа, аутентификацию и API-ключи и выдаёт отчёт с уязвимостями и рекомендациями по исправлению. CX Codex +1 1 020установок database-reviewer sangrokjung Субагент database-reviewer для Claude Code, который проверяет SQL-миграции, индексы и политики RLS в проектах на PostgreSQL и Supabase. Помогает находить N+1 и оценивать планы через EXPLAIN ANALYZE. CX Codex ★ 880звёзд репо supabase-audit-rls yoanbernabeu Скилл supabase-audit-rls для Claude Code проверяет политики Row Level Security в Supabase на обходы и типичные ошибки настройки. Работает с живой базой, пока таблицы уже отдают данные наружу. CX Codex +1 1 300установок supabase-audit-tables-read yoanbernabeu Скилл supabase-audit-tables-read для Claude Code и пяти других платформ проверяет, какие таблицы Supabase отдают данные без аутентификации и насколько эффективны политики RLS. CX Codex +1 533установок supabase-postgres-best-practices supabase Скилл supabase-postgres-best-practices помогает агенту проектировать схемы и писать SQL с учётом правил Supabase для Postgres. Подключайте его до изменений базы и при разборе проблем с запросами, подключениями или RLS. CX Codex +1 146установок database-schema-designer OneWave-AI Скилл database-schema-designer проектирует реляционные и документные схемы баз данных по требованиям или коду проекта. Помогает составить таблицы, связи, строгие ограничения и миграции. CX Codex +1 432установок

Из того же набора106

Весь набор →
zod-validation Скилл zod-validation учит агента синтаксису и правилам Zod v4 в TypeScript. Пригодится при составлении схем данных, валидации форм, парсинге API и конвертации схем в JSON Schema. CX Codex +1 222установок tanstack-form Помогает собирать формы на TanStack Form v1 в React и управлять их состоянием, валидацией и отправкой. Описывает работу со сложными и динамическими формами. CX Codex +1 222установок knowledge-graph-builder Скилл knowledge-graph-builder для Claude Code проектирует граф знаний, помогает выбрать графовую БД и связать обход графа с векторным поиском. Решает задачи Graph RAG и проверки фактов. CX Codex +1 222установок pino-logging Скилл pino-logging помогает настроить структурированные логи Pino в Node.js: от контекста запросов и маскировки секретов до вывода в разные места. CX Codex +1 217установок typescript-patterns Скилл typescript-patterns учит ИИ-агента сложным приёмам TypeScript в строгом режиме. Он помогает избежать сбоев во время выполнения за счёт проверок на этапе сборки. CX Codex +1 202установок react-patterns Скилл react-patterns по React 19+: паттерны хуков, выбор управления состоянием, загрузка данных через use() и борьба с лишними ре-рендерами. CX Codex +1 201установок ci-cd-architecture Скилл ci-cd-architecture помогает спроектировать CI/CD-пайплайн, выбрать платформу деплоя и настроить безопасность GitHub Actions. Пригодится при запуске и развитии проекта. CX Codex +1 199установок openapi Настраивает агента на проектирование спецификаций OpenAPI 3.1 и генерацию TypeScript-клиентов. Помогает писать схемы контрактов и документацию для REST API. CX Codex +1 197установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой