database-security

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

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.
专注于行级安全(RLS)实施、零信任数据库架构和取证审计追踪的数据库安全审计工具。重点关注Supabase、Postgres和Convex数据层安全。如果是通用应用安全需求(如OWASP Top 10、认证模式、安全标头、输入验证),请使用
security
技能。

Quick Reference

快速参考

NeedApproach
RLS enforcementEnable on every public table; separate policies per operation
RLS performanceIndex RLS columns; wrap auth.uid() in (select ...) subselect
Zero-Trust DBMicro-segmentation, identity propagation, TLS enforcement
Supabase auth in RLSUse (select auth.uid()) and auth.jwt(); never auth.role()
Convex auth guardsCall ctx.auth.getUserIdentity() in every public function
JIT accessTime-bound grants that expire automatically
Audit trailsDatabase triggers with immutable audit_log table
PGAuditExtension for statement-level and object-level SQL auditing
Service role safetyNever use service_role key in client-side code
Views and RLSUse security_invoker = true (Postgres 15+) to enforce RLS
Schema segmentationSeparate public, private, and audit schemas
Database complianceRLS + audit logging + encryption satisfies multiple frameworks
需求实现方法
RLS实施在所有公开表上启用;为每个操作设置独立策略
RLS性能优化为RLS相关列建立索引;将auth.uid()包裹在(select ...)子查询中
零信任数据库微分段、身份传播、强制启用TLS
Supabase RLS中的认证使用(select auth.uid())和auth.jwt(); 切勿使用auth.role()
Convex认证防护在所有公开函数中调用ctx.auth.getUserIdentity()
即时(JIT)访问控制自动过期的限时权限授予
审计追踪搭配不可变audit_log表的数据库触发器
PGAudit配置用于语句级和对象级SQL审计的扩展
服务角色安全切勿在客户端代码中使用service_role密钥
视图与RLS使用security_invoker = true(Postgres 15+)来强制执行RLS
架构分段分离public、private和audit架构
数据库合规性RLS + 审计日志 + 加密可满足多种合规框架要求

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
执行数据库安全审计时,请遵循以下步骤:
  1. 攻击面映射:识别数据层的所有入口点(公开API、内部仪表板、AI Agent、定时任务)
  2. RLS覆盖检查:查询pg_tables以验证所有public架构表均已启用RLS并配置了合适的策略
  3. 策略审查:检查是否存在逻辑绕过、缺失WITH CHECK子句、权限过度宽松的FOR ALL策略
  4. 服务角色审计:在客户端代码中搜索service_role密钥泄露情况;验证其仅出现在服务端代码中
  5. 函数审计:检查暴露架构中的security definer函数以及缺失认证防护的Convex函数
  6. 访问模拟:以anon和已认证角色执行查询,验证策略是否生效
  7. 视图审计:验证视图是否设置了security_invoker = true,或未处于暴露架构中
  8. 审计追踪验证:确认触发器或PGAudit捕获了所有与安全相关的操作
  9. 合规性验证:将数据库控制措施与适用的监管框架进行映射

Security Principles

安全原则

PrincipleDatabase Application
Defense in DepthRLS + application checks + schema segmentation
Least PrivilegeMinimal GRANT per role; anon gets near-zero access
Zero TrustVerify identity at DB level even for internal requests
Secure by DefaultRLS enabled on creation; default-deny when no policy
Fail SecurelyPostgres default-deny on RLS; generic error responses
Assume BreachDesign assuming attacker has a valid JWT
原则数据库应用实践
纵深防御RLS + 应用层检查 + 架构分段
最小权限为每个角色授予最小权限;anon角色仅拥有极少量访问权限
零信任即使是内部请求,也要在数据库层面验证身份
默认安全创建表时默认启用RLS;无策略时默认拒绝访问
安全失效Postgres在RLS下默认拒绝访问;返回通用错误响应
假设已泄露基于攻击者已获取有效JWT的前提进行设计

Anti-Patterns

反模式

Anti-PatternRisk
Security by obscurity (UUIDs only)Attackers enumerate IDs via IDOR
Anon role with SELECT on sensitive tablesPublic data exposure via Supabase API
RLS columns without indexesProduction performance degradation (100x+)
Frontend-only permission checksAttackers bypass via direct API calls
Standing admin privilegesExcessive blast radius if compromised
service_role key in client-side codeBypasses all RLS policies completely
FOR ALL policies instead of per-operationUnintended write access through broad rule
Security definer functions in public schemaFunctions callable from API, bypass RLS
Views without security_invokerViews bypass RLS silently
反模式风险
通过模糊性实现安全(仅依赖UUID)攻击者可通过IDOR枚举ID
anon角色拥有敏感表的SELECT权限敏感数据通过Supabase API公开暴露
RLS相关列未建立索引生产环境性能大幅下降(100倍以上)
仅在前端进行权限检查攻击者可通过直接调用API绕过检查
长期管理员权限若权限泄露,影响范围极大
客户端代码中使用service_role密钥完全绕过所有RLS策略
使用FOR ALL策略而非分操作策略宽泛的规则可能导致意外的写入权限
公开架构中的security definer函数函数可通过API调用,绕过RLS
未设置security_invoker的视图视图会静默绕过RLS

Common Mistakes

常见错误

MistakeCorrect 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 policiesCreate separate SELECT, INSERT, UPDATE, DELETE policies for clarity and safety
Leaving anon role with SELECT on sensitive tablesRestrict anon access; require authenticated role for sensitive data
Relying on UUIDs as the only access controlEnforce RLS policies and explicit auth checks alongside unique identifiers
No index on columns used in RLS USING clausesAdd B-tree indexes on all columns referenced in RLS policy expressions
Convex function missing ctx.auth.getUserIdentity() callEvery public query and mutation must validate identity before accessing data
Using service_role key in client-side codeUse anon key client-side; service_role only in server-side functions
Views bypassing RLS without security_invokerSet security_invoker = true on views in Postgres 15+
Security definer functions in exposed schemasPlace security definer functions in non-exposed schemas with search_path = ''
No audit logging for security-relevant database eventsUse triggers and PGAudit to capture all data access and modifications
错误正确实践
未用(select ...)包裹就使用auth.uid() = user_id使用(select auth.uid()) = user_id,以便Postgres通过initPlan缓存结果
使用FOR ALL策略而非独立的分操作策略为SELECT、INSERT、UPDATE、DELETE分别创建独立策略,确保清晰性和安全性
允许anon角色拥有敏感表的SELECT权限限制anon角色访问;敏感数据需已认证角色才能访问
仅依赖UUID作为唯一访问控制手段在使用唯一标识符的同时,强制执行RLS策略和显式认证检查
RLS USING子句中引用的列未建立索引为RLS策略表达式中引用的所有列添加B树索引
Convex函数未调用ctx.auth.getUserIdentity()所有公开查询和变更操作必须在访问数据前验证身份
客户端代码中使用service_role密钥客户端使用anon密钥;service_role仅在服务端函数中使用
视图未设置security_invoker导致绕过RLS在Postgres 15+版本的视图上设置security_invoker = true
暴露架构中的security definer函数将security definer函数放置在非暴露架构中,并设置search_path = ''
未对安全相关数据库事件进行审计日志记录使用触发器和PGAudit捕获所有数据访问和修改操作

Relationship to Security Skill

与Security技能的关系

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.).
application-security
技能涵盖通用应用安全:OWASP Top 10、认证模式、输入验证、安全标头以及合规性概述。本
database-security
技能作为补充,专注于数据库层面的问题:RLS策略设计与性能优化、Supabase/Postgres特定模式、Convex认证防护、PGAudit配置以及数据库特定的合规性实现(如GDPR擦除的SQL函数、HIPAA PHI审计触发器等)。

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
  • 通过访问模拟验证RLS实施:使用
    Task
    Agent对所有公开表执行匿名和已认证查询
  • 审计Convex函数是否缺失认证防护:使用
    Explore
    Agent扫描所有查询和变更处理程序,检查是否存在getUserIdentity调用
  • 设计零信任数据库架构:使用
    Plan
    Agent映射架构、访问策略、JIT权限授予和审计日志设计
  • 生成数据库合规性证据:使用
    Task
    Agent运行审计查询并生成合规报告

References

参考资料

  • rls-performance.md -- RLS policy performance, initPlan caching, stable functions, separate policies, EXPLAIN benchmarking
  • zero-trust-database.md -- Micro-segmentation, identity propagation, connection security, JIT access controls
  • audit-logging.md -- Trigger-based auditing, PGAudit extension and log classes, log integrity, tamper-proof storage
  • convex-security.md -- Identity validation, manual RLS in functions, granular functions, role-based access via JWT claims
  • threat-modeling.md -- STRIDE applied to database access, RLS bypass vectors, data layer trust boundaries
  • application-security.md -- Service role management, schema exposure, security definer functions, views and RLS
  • compliance-frameworks.md -- Database-specific GDPR, HIPAA, SOC2, PCI-DSS requirements and SQL implementations
  • rls-performance.md -- RLS策略性能、initPlan缓存、稳定函数、独立策略、EXPLAIN基准测试
  • zero-trust-database.md -- 微分段、身份传播、连接安全、JIT访问控制
  • audit-logging.md -- 基于触发器的审计、PGAudit扩展与日志类别、日志完整性、防篡改存储
  • convex-security.md -- 身份验证、函数中的手动RLS、细粒度函数、基于JWT声明的角色访问控制
  • threat-modeling.md -- STRIDE模型在数据库访问中的应用、RLS绕过向量、数据层信任边界
  • application-security.md -- 服务角色管理、架构暴露、security definer函数、视图与RLS
  • compliance-frameworks.md -- 数据库特定的GDPR、HIPAA、SOC2、PCI-DSS要求及SQL实现