Communitygithub.com

lguidolin/postgres-postgraphile-rls-and-sql

PostgreSQL, PostGraphile 설정, Row-Level Security 정책, SQL 스키마 파일 작성 또는 Browser→App→PostGraphile→Postgres 데이터 경로 작업 시 사용합니다. 키워드: RLS, SECURITY DEFINER, search_path, pgSettings, grants, roles, GraphQL 깊이 제한, 쿼리 비용, statement_timeout, SQL 파일 구성.

postgres-postgraphile-rls-and-sql란 무엇인가요?

이 스킬은 PostGraphile과 PostgreSQL을 기반으로 하는 스택에서 데이터 계층 메커니즘을 정의합니다. **심층 방어** 원칙에 따라 RLS를 최종 보안 계층으로 사용하며, 데이터는 **Browser→App 서버→PostGraphile→PostgreSQL**의 단일 경로를 통해서만 접근합니다. 앱 계층의 인가 로직은 UX를 위한 사전 검사일 뿐이며, 실제 보안은 데이터베이스의 RLS 정책이 담당합니다. 이 스킬은 또한 SQL 스타일 가이드(객체별 파일, 의존성 순서 포함, 인라인 문서화), 보안 설정(SEARCH_PATH 강제, statement_timeout, GraphQL 깊이/비용 제한, 프로덕션에서 introspection 비활성화), 그리고 역할 모델(비로그인, 로그인, 조직 포함, 연결 전용, 마이그레이션 전용)을 포함합니다. Claude Code, Cursor, Codex 등 다양한 AI 에이전트 플랫폼에서 이 규칙을 적용하여 일관된 데이터 액세스 패턴을 유지하고 보안 취약점을 최소화할 수 있습니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/lguidolin/agent-skills/tree/main/skills/postgres-postgraphile-rls-and-sql

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Postgres, PostGraphile, RLS 및 SQL

개요

이 스택의 데이터 계층 메커니즘입니다. 심층 방어(RLS를 최종 방어선으로 사용)와 하나의 합법적 데이터 경로를 구현합니다. 스택에 특화되어 있으며, PostGraphile/Postgres가 없는 프로젝트에는 적용되지 않습니다.

데이터 경로

브라우저 → 앱 서버 → PostGraphile → PostgreSQL. 정확히 하나의 합법적 경로입니다.

  • 브라우저는 GraphQL/DB에 직접 접근하지 않으며, 앱은 애플리케이션 데이터를 위해 DB에 직접 쿼리하지 않습니다.
  • 앱은 세션 컨텍스트를 헤더로만 전달(사용자 ID, 조직 힌트)합니다. 앱에 인가 로직이 없으며, 컨텍스트는 다운스트림에서 검증되고 신뢰되지 않습니다.
  • 단일 경로 = 인증 컨텍스트, 검증, RLS를 적용할 수 있는 단일 지점입니다. 사이드 채널은 이러한 강제를 우회하는 구멍입니다.

보안 규칙

  • RLS는 최종 적용 계층입니다. 앱 계층의 검사는 UX를 위한 것이며, 데이터베이스가 방어벽입니다. 상위 계층의 버그가 발생해도 다른 테넌트의 행이 유출되지 않습니다.
  • 역할은 실제 세션 상태를 모델링합니다. 로그인하지 않음, 조직 없이 로그인, 조직과 함께 로그인, 연결 전용 역할, 마이그레이션 전용 역할. 역할은 의미를 가집니다.
  • 권한 있는 연결 역할은 애플리케이션 쿼리를 실행하지 않습니다. 앱 쿼리는 제한되고 RLS가 적용되는 역할로 실행됩니다.
  • SECURITY DEFINER 함수는 search_path를 정의 내에 인라인으로 설정합니다. 매번, 예외 없이.
  • 값이 없으면 NULL이지, 빈 문자열이 아닙니다. 빈 문자열 센티넬은 금지됩니다. 값이 없으면 값을 생략하세요.
  • GraphQL은 DoS 공격 표면입니다. 제한하세요. 쿼리 깊이 제한과 비용/복잡성 분석을 적용하고, 예산을 초과하는 쿼리는 거부하세요. 페이지네이션 크기를 제한하세요. 앱 역할에 대해 DB **statement_timeout**을 설정하세요. 의도적으로 필요하지 않은 한 프로덕션에서 introspection을 비활성화하세요.

SQL 스타일

  • 파일당 하나의 객체 — 각 테이블, 함수, 정책, 권한 부여 집합은 자체 파일에 있습니다.
  • schema/object_type/name 구조로 구성 — 디렉토리가 데이터베이스의 구성을 반영합니다.
  • 포함 순서는 의존성 순서입니다. include 매니페스트는 목차 역할을 합니다.
  • 인라인으로 문서화하세요. COMMENT ON은 객체와 같은 파일에 위치합니다. 무엇과 왜를 설명하세요.
  • 설명적인 별칭(테이블 이름의 단수형, 단일 문자 아님); Postgres 관용구(current_* getter)를 따르십시오.
  • 타입과 사용자 대상 역할은 하드코딩된 제약 조건이 아닌 데이터입니다. — FK로 검증되고 스키마 변경 없이 확장 가능한 키/레이블/설명이 있는 조회 테이블입니다.

빠른 참조

규칙확인 사항
새 SECURITY DEFINER 함수search_path가 인라인으로 설정되었습니까?
테넌트 데이터가 있는 새 테이블RLS 정책 + 거부 테스트(graphql-contract-testing 참조)가 있습니까?
값이 없음NULL이지 ''가 아닌가요?
새로운 GraphQL 표면깊이/비용 제한 및 페이지네이션 상한이 있습니까?
새 객체자체 파일, 의존성 순서에 따른 include, 인라인 COMMENT ON이 있습니까?

전체 근거: engineering-constitution/references/engineering-constitution.md에 번들된 헌법 제XIII, XIV, XVIII조. 마이그레이션: zero-downtime-migrations. 계약 테스트: graphql-contract-testing.

Individual skills in this repo

This repo contains 18 individual skills — each has its own dedicated page.

lguidolin/change-hygiene-and-code-craft

Use when writing or refactoring code, structuring a commit or PR, or deciding whether to abstract duplication. Symptoms — mixing reorg with logic changes, a PR doing several things at once, a file growing large, the second copy of similar code, or unsure whether to DRY something up.

lguidolin/cloud-delivery-aks

Use when deploying to Kubernetes or Azure Kubernetes Service (AKS), configuring cloud secrets, setting up progressive rollout/canary, per-PR ephemeral environments, or k8s health probes. Keywords — Kubernetes, AKS, Key Vault, Argo Rollouts, Flagger, canary, blue-green, liveness, readiness, PodDisruptionBudget, HPA, rollback, GHCR.

lguidolin/commit-history-rewrite

Use when an existing repository has messy commit history that needs to conform to conventional commits before adopting release-please, or when intermediate WIP/fixup/merge commits need to be cleaned up.

lguidolin/conventional-commits-and-releases

Use when committing, writing a commit message, opening a PR that will be squash-merged, or configuring automated versioning/changelogs. Keywords — conventional commits, release-please, semver, feat/fix/chore, breaking change, changelog.

lguidolin/defense-in-depth-security

Use when handling untrusted input, secrets, authentication/authorization, or dependencies — or threat-modeling a new surface. Keywords — STRIDE, threat model, least privilege, secrets management, supply chain, dependency scanning, input validation, audit log, defense in depth.

lguidolin/designing-before-building

Use when starting a feature, fixing a non-trivial bug, or about to write implementation code — before any code exists. Symptoms you need this: "this is simple, I'll just code it", reaching for the editor before a design is approved, or an idea that hasn't been turned into a spec and plan.

lguidolin/engineering-constitution

Use when starting work in a project that follows the engineering constitution, orienting to its rules, or deciding which engineering practice applies to a task — spec writing, commits, testing, security, deploys, database, or UI work.

lguidolin/graphql-contract-testing

Use when writing a GraphQL query/mutation that the UI and a test will share, or building route/schema contract or smoke tests. Symptoms — copying a query into a test, a test asserting on query text, schema change that didn't break the UI build, or RLS/permission drift. Keywords — graphql-codegen, typed document, contract test, route smoke test.

lguidolin/init-repo-CI

Use when setting up a new repository with conventional commits, release-please, and CI automation, or when retrofitting an existing repository that lacks automated versioning and PR validation workflows.

lguidolin/interface-craft-and-accessibility

Use when building or styling UI — components, layouts, forms, design tokens — or making accessibility decisions. Keywords — a11y, WCAG, keyboard navigation, focus state, contrast, design system, minimalist UI, component reuse, ARIA, semantic HTML.

lguidolin/merge-gates-and-automation

Use when setting up or changing CI, pre-push hooks, or a task runner, or deciding what must pass before merge. Symptoms — tempted to put authoritative checks only in a local hook, skip CI, bypass with --no-verify, or unsure what gates a merge vs. runs locally.

lguidolin/observability-and-slos

Use when adding logging, metrics, tracing, health checks, SLOs, or alerting — or when building a service surface that needs to be operable and debuggable. Keywords — structured logs, OpenTelemetry, correlation id, RED metrics, liveness, readiness, SLI, SLO, error budget, alerting.

lguidolin/performance-and-scale

Use when working on hot paths, list endpoints, pagination, data-access in loops, or public interfaces/schemas. Symptoms — unbounded queries, N+1 access, no latency budget, optimizing without measuring, or changing an interface many consumers depend on. Keywords — pagination, N+1, Hyrum's Law, performance budget, bundle size.

lguidolin/recording-decisions

Use when a design or architecture decision has been made and needs to be captured — writing a decision record or ADR, updating a decision index, noting a deferred idea, or superseding a past decision. Keywords — ADR, decision record, rationale, rejected alternatives, dependency index.

lguidolin/resilience-and-deploy-safety

Use when planning a deploy, designing a rollback, or responding to an incident or writing a postmortem. Keywords — deploy safety, rollback, immutable artifact, progressive delivery, canary, blast radius, incident response, blameless postmortem, error budget.

lguidolin/ship-it

Use when the user wants to ship work — push, PR, archive decision records, merge, and clean up. Handles the full lifecycle from committing final changes through post-merge cleanup including converting specs/plans to compact decision records.

lguidolin/tests-as-a-control

Use when writing or modifying tests, when a test breaks during a refactor, or when testing permission/role rules. Symptoms — tempted to edit a test to make it pass, testing only the happy path, a deny-test that started passing, flaky tests, or unsure what to assert.

lguidolin/zero-downtime-migrations

Use when changing a database schema where data must survive the change — adding/removing/renaming columns, constraints, indexes, or backfilling. Symptoms — a destructive migration bundled with a code deploy, a NOT NULL column with a backfill, a table-locking UPDATE, or a rename. Keywords — expand/contract, parallel change, backfill, NOT VALID, CREATE INDEX CONCURRENTLY, graphile-migrate.

관련 스킬