permdock 0.25.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/2020-bJfT8aIA.js +6760 -0
- package/dist/a2a/index.d.ts +5 -9
- package/dist/a2a/index.js +13 -15
- package/dist/adapter-context-lHq_i_77.js +28 -0
- package/dist/adoption-scan-b0_Xpab8.js +106 -0
- package/dist/agent/index.d.ts +2 -2
- package/dist/agent/index.js +1 -1
- package/dist/ai-sdk/index.d.ts +4 -6
- package/dist/ai-sdk/index.js +6 -7
- package/dist/annotate-doc-BCOCOrq_.js +214 -0
- package/dist/annotate-routes-BvSuEht3.js +75 -0
- package/dist/annotate-uZVGIRym.js +25 -0
- package/dist/app/index.d.ts +2 -103
- package/dist/app/index.js +1 -114
- package/dist/app-data-DbSPSPIl.js +62 -0
- package/dist/approval-header-BvszJE3l.js +25 -0
- package/dist/approval-normalize-Cpp8R0rY.js +190 -0
- package/dist/approval-prompt-C-vjNZyd.d.ts +57 -0
- package/dist/approval-prompt-Covyx_DB.js +60 -0
- package/dist/approval-required-B-R4Yw3J.js +5 -0
- package/dist/approvals/index.d.ts +5 -5
- package/dist/approvals/index.js +8 -8
- package/dist/approvals-7jHYXocE.js +1039 -0
- package/dist/approvers-BkY_ZfWl.js +76 -0
- package/dist/arazzo-DMmcumRx.js +76 -0
- package/dist/arazzo-Hxerfx3_.js +35 -0
- package/dist/args-0EWFk-4S.js +311 -0
- package/dist/astro/index.d.ts +6 -8
- package/dist/astro/index.js +3 -4
- package/dist/audience-DauhRBNg.js +54 -0
- package/dist/auth-WHKYWtnS.js +187 -0
- package/dist/authz-topic-D8x24Jv-.js +14 -0
- package/dist/authzen/index.d.ts +37 -22
- package/dist/authzen/index.js +69 -27
- package/dist/automation-CUcWz8uu.d.ts +122 -0
- package/dist/automation-CpPdFX91.js +157 -0
- package/dist/base-url--yJPQlIK.js +8 -0
- package/dist/better-auth/index.d.ts +2 -8
- package/dist/better-auth/index.js +10 -13
- package/dist/better-supabase/index.d.ts +141 -95
- package/dist/better-supabase/index.js +239 -794
- package/dist/better-supabase-DSbs4MtQ.js +201 -0
- package/dist/bind-B3MHrzw4.d.ts +56 -0
- package/dist/bind-up3QptTt.js +124 -0
- package/dist/body-W1_8r6Tw.js +9 -0
- package/dist/body-text-B-m3p-qY.js +55 -0
- package/dist/boundary--5Swp7sN.js +18 -0
- package/dist/boundary-DJqHADKu.d.ts +22 -0
- package/dist/budget-5LJ8kfZk.d.ts +12 -0
- package/dist/budget-BH81q2cj.js +19 -0
- package/dist/build-instance-hLKYe3-E.js +30 -0
- package/dist/canonical-json-BibZkXtE.js +28 -0
- package/dist/capability-CVt3lpVK.d.ts +128 -0
- package/dist/capability-_ZsyfYxU.js +204 -0
- package/dist/casbin-CYwbggCS.js +29 -0
- package/dist/casbin-Co1KcLWU.js +241 -0
- package/dist/casl-CrltbDPa.js +23 -0
- package/dist/casl-D7n7yE-h.js +307 -0
- package/dist/catalog/index.d.ts +6 -20
- package/dist/catalog/index.js +13 -15
- package/dist/catalog-B3MJShnZ.js +51 -0
- package/dist/catalog-CgK_L4Qf.js +1 -0
- package/dist/catalog-DyC3LKc7.js +130 -0
- package/dist/catalog-doc-Bp5khmCG.js +352 -0
- package/dist/catalog-fingerprint-DAWZARy6.js +31 -0
- package/dist/catalog-operations-dxuOZr4J.js +59 -0
- package/dist/catalog-path-bG0XxHMu.js +11 -0
- package/dist/challenge-CjwmjcuX.js +518 -0
- package/dist/chat/index.d.ts +1 -1
- package/dist/chat/index.js +10 -13
- package/dist/chat-sdk/index.d.ts +3 -11
- package/dist/chat-sdk/index.js +7 -11
- package/dist/checks-DSm45qH7.js +71 -0
- package/dist/claims-map-BGbpbvGD.js +15 -0
- package/dist/claims-map-CLKQWxJG.d.ts +33 -0
- package/dist/claims-size-DcjhvUv5.js +58 -0
- package/dist/claude-agent/index.d.ts +3 -5
- package/dist/claude-agent/index.js +4 -5
- package/dist/clerk/index.d.ts +4 -8
- package/dist/clerk/index.js +7 -8
- package/dist/cli/bin.js +6 -7
- package/dist/cli/generate/watch-worker.d.ts +20 -0
- package/dist/cli/generate/watch-worker.js +69 -0
- package/dist/cli/index.d.ts +11 -20
- package/dist/cli/index.js +8 -8
- package/dist/cli/plugins/app.d.ts +18 -0
- package/dist/cli/plugins/app.js +26 -0
- package/dist/cli/plugins/better-supabase.d.ts +10 -0
- package/dist/cli/plugins/better-supabase.js +18 -0
- package/dist/cli/plugins/openapi.d.ts +19 -0
- package/dist/cli/plugins/openapi.js +40 -0
- package/dist/cli/plugins/powersync.d.ts +7 -0
- package/dist/cli/plugins/powersync.js +29 -0
- package/dist/cli/plugins/rls.d.ts +8 -0
- package/dist/cli/plugins/rls.js +27 -0
- package/dist/cli/plugins/schemas.d.ts +13 -0
- package/dist/cli/plugins/schemas.js +23 -0
- package/dist/cli/plugins/scim.d.ts +10 -0
- package/dist/cli/plugins/scim.js +32 -0
- package/dist/cli/plugins/supabase-hook.d.ts +13 -0
- package/dist/cli/plugins/supabase-hook.js +40 -0
- package/dist/cli/plugins/supabase.d.ts +27 -0
- package/dist/cli/plugins/supabase.js +69 -0
- package/dist/cli/plugins/ui.d.ts +11 -0
- package/dist/cli/plugins/ui.js +19 -0
- package/dist/client-V95IvZsF.d.ts +43 -0
- package/dist/client-subject-v89t811z.d.ts +25 -0
- package/dist/clients-Bb_33pRE.js +22 -0
- package/dist/clients-DGcyFDCc.d.ts +10 -0
- package/dist/cloud/index.d.ts +8 -26
- package/dist/cloud/index.js +22 -28
- package/dist/cloud-BfEI9TLS.js +85 -0
- package/dist/codemod-DwH0IZ2x.js +2159 -0
- package/dist/codemod-p67ePW25.js +35 -0
- package/dist/collect-BJZsuBW4.js +535 -0
- package/dist/collect-CPvCXMQ-.js +1 -0
- package/dist/collect-CpGnmGpL.js +54 -0
- package/dist/command-9GAzSI7E.js +5 -0
- package/dist/compact-C4LFuqbW.js +28 -0
- package/dist/compare-dfHDj8kT.js +11 -0
- package/dist/compile/index.d.ts +2 -2
- package/dist/compile/index.js +1 -1
- package/dist/compile-BUKXrueE.js +685 -0
- package/dist/compile-Blrr5WWw.js +724 -0
- package/dist/compile-D8c1nFGy.d.ts +118 -0
- package/dist/completion-CfrZOGcB.js +150 -0
- package/dist/conditions-CkHgXoZB.js +385 -0
- package/dist/config-D6gh_xvs.js +25 -0
- package/dist/config-iyy90IOU.js +143 -0
- package/dist/config-report-BaHEBpt-.js +55 -0
- package/dist/config-shape-B6tdyBju.js +149 -0
- package/dist/connection-BnoSqYU1.js +196 -0
- package/dist/connector-schema-BSRMyq4M.js +433 -0
- package/dist/constants-PCJiir_3.js +19 -0
- package/dist/context-DmH-Eyvx.js +95 -0
- package/dist/convex/index.d.ts +5 -9
- package/dist/convex/index.js +7 -8
- package/dist/core-CnC47rSf.d.ts +200 -0
- package/dist/core-DKqrD_xW.js +338 -0
- package/dist/coverage-DL7JCZmb.d.ts +133 -0
- package/dist/coverage-nFSMjFxH.js +42 -0
- package/dist/create-BAMPoEga.js +133 -0
- package/dist/create-BsRcXm_m.d.ts +125 -0
- package/dist/create-D3oXoXxM.js +373 -0
- package/dist/create-DeQ5t8mZ.d.ts +124 -0
- package/dist/create-sGl1ccTp.d.ts +185 -0
- package/dist/credential-ke0KMQeB.js +430 -0
- package/dist/credentials-6ZWbJ-Re.js +72 -0
- package/dist/credentials-BfzdL5kv.d.ts +123 -0
- package/dist/credentials-DOeqknte.js +309 -0
- package/dist/decide-set-CgNcE6pP.js +99 -0
- package/dist/deciding-columns-BnglEKqU.js +143 -0
- package/dist/decision-hHv4UZgy.js +20 -0
- package/dist/define-permdock-BLpQ0m95.d.ts +99 -0
- package/dist/define-permdock-CIxHBykk.js +148 -0
- package/dist/definition-options-9o8Hdww3.js +370 -0
- package/dist/delegation-BaUNCrE_.js +263 -0
- package/dist/delegation-input-7Y5Rlja7.js +18 -0
- package/dist/delivery/index.d.ts +4 -4
- package/dist/delivery/index.js +5 -5
- package/dist/delivery-Cb3VCij5.js +555 -0
- package/dist/delivery-event-D5b9yhaJ.js +39 -0
- package/dist/denied-text-D6JJTDr3.d.ts +20 -0
- package/dist/describe-B7EosIKA.js +100 -0
- package/dist/describe-lAafaRQQ.d.ts +43 -0
- package/dist/device-f3JEnqa0.js +195 -0
- package/dist/diff-BIqibFnm.js +464 -0
- package/dist/diff-n6LONVwL.js +36 -0
- package/dist/digest-BaP8bQzX.js +26 -0
- package/dist/digest-BcIZRYvp.d.ts +17 -0
- package/dist/doctor-Bg12v-8M.js +4847 -0
- package/dist/doctor-DCsyH7YR.js +53 -0
- package/dist/drizzle/index.d.ts +5 -9
- package/dist/drizzle/index.js +5 -6
- package/dist/elysia/index.d.ts +6 -8
- package/dist/elysia/index.js +6 -7
- package/dist/env-hbYumkRp.js +7 -0
- package/dist/errors-DOSkVeTC.js +127 -0
- package/dist/errors-DUJ7wLlE.d.ts +137 -0
- package/dist/errors-Da88YLm5.js +26 -0
- package/dist/errors-DgLOqc6j.js +148 -0
- package/dist/errors-KngVdJT9.d.ts +12 -0
- package/dist/evaluate-D8SdfP3h.js +1948 -0
- package/dist/evaluations-BQkpE7hC.js +609 -0
- package/dist/evaluations-K9qglDP7.d.ts +36 -0
- package/dist/evaluator-Dlhn2d7D.js +2 -0
- package/dist/evaluator-eager-UuJK6NX_.js +8 -0
- package/dist/eve/index.d.ts +11 -10
- package/dist/eve/index.js +7 -8
- package/dist/event-time-ChIrhzy5.js +26 -0
- package/dist/execute-SN8_dlch.js +166 -0
- package/dist/express/index.d.ts +6 -8
- package/dist/express/index.js +6 -7
- package/dist/fastify/index.d.ts +5 -11
- package/dist/fastify/index.js +6 -8
- package/dist/fetch-adapter-gmTCu4FR.d.ts +32 -0
- package/dist/fetch-adapter-ovZdSvlT.js +124 -0
- package/dist/fields-6d1j-q3c.js +502 -0
- package/dist/fields-C0L2FoZk.js +25 -0
- package/dist/files-DAR51W3J.js +157 -0
- package/dist/files-DuV7wRim.js +139 -0
- package/dist/fixtures-Bm0G0A7H.js +79 -0
- package/dist/flags-C0e-BzGW.js +112 -0
- package/dist/freeze-DGfJq_j2.js +86 -0
- package/dist/from-snapshot-CCDF_ihX.js +173 -0
- package/dist/gen-B4GUqsfM.js +1160 -0
- package/dist/gen-BC66z5Fd.js +1 -0
- package/dist/gen-kind-Bahz_i3U.js +67 -0
- package/dist/gen-kind-DFQnQwFN.d.ts +13 -0
- package/dist/generate-5_kz2309.js +305 -0
- package/dist/generate-B-msjuaO.js +2339 -0
- package/dist/generate-CbtjKcjn.js +67 -0
- package/dist/generate-DhP0jQDR.js +97 -0
- package/dist/generate-options-BDgadlwe.js +1104 -0
- package/dist/grantee-BPUG6f0r.js +109 -0
- package/dist/grantee-conditions-Dob6QQAc.js +270 -0
- package/dist/grantee-match-CFQ-LRcL.js +147 -0
- package/dist/grants-BzjbUCdR.js +139 -0
- package/dist/graph-sql-Ds3nbevr.d.ts +27 -0
- package/dist/h3/index.d.ts +4 -6
- package/dist/h3/index.js +4 -5
- package/dist/headers-D1oRr-js.d.ts +8 -0
- package/dist/helpers-DSmj6SHi.js +533 -0
- package/dist/hono/index.d.ts +6 -8
- package/dist/hono/index.js +7 -8
- package/dist/hook-sql-BIR4fL7i.js +3412 -0
- package/dist/hosted-DMJKJPoc.js +361 -0
- package/dist/hosted-DUbuh0Td.d.ts +100 -0
- package/dist/http-BUIYu1Kc.d.ts +10 -0
- package/dist/http-BbX_Ou3_.js +48 -0
- package/dist/http-C9jDw_bZ.js +82 -0
- package/dist/http-dNltTpC8.js +71 -0
- package/dist/ids-0QDIxtxL.js +53 -0
- package/dist/import-BZi1tZxq.js +318 -0
- package/dist/import-BqoDHpFt.js +1158 -0
- package/dist/index-BXz-XXC3.d.ts +1108 -0
- package/dist/index-CVuc3E1O.d.ts +196 -0
- package/dist/index-Cq9N5B92.d.ts +506 -0
- package/dist/index-D8A1d_Tt.d.ts +214 -0
- package/dist/index-DegTwZxD.d.ts +93 -0
- package/dist/index-O0qbI8Ha.d.ts +221 -0
- package/dist/index.d.ts +24 -25
- package/dist/index.js +47 -46
- package/dist/init-9cqnSJWG.js +95 -0
- package/dist/init-K3tKOwf4.js +94 -0
- package/dist/instance-options-B4MD2wgl.d.ts +9 -0
- package/dist/instance-options-CLErhA76.js +23 -0
- package/dist/instance-snapshot-DdGOpSfN.js +716 -0
- package/dist/instant-Ih5riY_A.js +18 -0
- package/dist/interactive-only-BZu9rLpa.js +1567 -0
- package/dist/internals-D58TnmDB.js +19 -0
- package/dist/json-schema-SDkWXxhu.d.ts +38 -0
- package/dist/json-schema-jtX26ydD.js +148 -0
- package/dist/jwt/index.d.ts +6 -24
- package/dist/jwt/index.js +18 -26
- package/dist/kernel-Dn6pKMAF.js +423 -0
- package/dist/kysely/index.d.ts +5 -9
- package/dist/kysely/index.js +5 -6
- package/dist/lazy-provider-CydlnKkS.d.ts +4 -0
- package/dist/lazy-provider-DG5rMeqL.js +28 -0
- package/dist/limits-DpTxX6N4.js +166 -0
- package/dist/live-options-CIUmc-YQ.js +70 -0
- package/dist/load-BPzIqlGB.js +1 -0
- package/dist/load-CZnlAyZ8.js +98 -0
- package/dist/load-jose-CjzIBSKI.js +7 -0
- package/dist/login-C1I5KIsK.js +67 -0
- package/dist/login-CP0UxnLw.js +255 -0
- package/dist/lru-Cp-AEvpR.js +27 -0
- package/dist/manifest-B-8d2lhG.js +45 -0
- package/dist/manifest-CRHphHxo.d.ts +362 -0
- package/dist/manifest-DvS2IoXo.js +399 -0
- package/dist/manifest-json-DMaBWmcG.js +8 -0
- package/dist/manifest-schema-DJY5Q_pR.js +507 -0
- package/dist/map-claims-BKdnPwep.js +386 -0
- package/dist/map-error-DTi_JZT8.js +22 -0
- package/dist/markers-C-kThnKN.js +79 -0
- package/dist/may-use-Died1tNU.js +233 -0
- package/dist/mcp/index.d.ts +11 -21
- package/dist/mcp/index.js +56 -43
- package/dist/membership-filter-CSKH48eD.js +66 -0
- package/dist/migrate-CmTMk7rd.js +536 -0
- package/dist/model-B4EKVHMK.js +188 -0
- package/dist/module-values-Ddx0GLaJ.js +106 -0
- package/dist/nest/index.d.ts +7 -13
- package/dist/nest/index.js +12 -15
- package/dist/next/client.d.ts +1 -3
- package/dist/next/client.js +2 -3
- package/dist/next/index.d.ts +36 -16
- package/dist/next/index.js +161 -31
- package/dist/next/plugin.d.ts +1 -3
- package/dist/next/plugin.js +3 -4
- package/dist/node/index.d.ts +6 -8
- package/dist/node/index.js +4 -5
- package/dist/oauth-security-C8fjzFRF.js +25 -0
- package/dist/ocsf-DKRQc6uv.js +135 -0
- package/dist/openai/index.d.ts +5 -7
- package/dist/openai/index.js +5 -6
- package/dist/openapi/index.d.ts +4 -16
- package/dist/openapi/index.js +4 -3
- package/dist/openapi-BHqqNSoG.js +95 -0
- package/dist/openapi-BT5XY7HY.js +260 -0
- package/dist/openapi-D2dmyWZK.js +411 -0
- package/dist/openapi-document-Ca5yAjc6.js +35 -0
- package/dist/operation-findings-D5Uo-dcm.js +35 -0
- package/dist/operation-risks-BD-j14dj.js +12 -0
- package/dist/operations-B0yO77Zz.js +290 -0
- package/dist/operations-BS8ExH5A.d.ts +58 -0
- package/dist/operations-De3F7tlf.js +88 -0
- package/dist/optional-CaQWp9HA.js +46 -0
- package/dist/orpc/index.d.ts +8 -12
- package/dist/orpc/index.js +10 -12
- package/dist/otel/index.d.ts +3 -5
- package/dist/otel/index.js +5 -7
- package/dist/output-djxu62oH.js +244 -0
- package/dist/output-files-C5LFnQa4.js +1 -0
- package/dist/output-files-DNid6TBl.js +197 -0
- package/dist/ownership-BO0sI5FB.js +558 -0
- package/dist/parse-local-manifest-BGLWVchi.d.ts +8 -0
- package/dist/parse-local-manifest-CfMjZAFi.js +67 -0
- package/dist/parse-nfHSt1Wy.js +149 -0
- package/dist/parse-request-IEEzVFM8.js +24 -0
- package/dist/parse-sink-events-B6nZx41L.js +125 -0
- package/dist/paths-CeS_gpHf.js +44 -0
- package/dist/pdp/index.d.ts +3 -9
- package/dist/pdp/index.js +22 -18
- package/dist/peer-BWTpSLs2.js +1 -0
- package/dist/peer-D77JpXe-.js +978 -0
- package/dist/perf-token-dFGVP14-.js +155 -0
- package/dist/permdock-BueSeg7X.js +1514 -0
- package/dist/permdock-Dz3yzWrp.d.ts +853 -0
- package/dist/permission-registry-DMYRZVcn.js +413 -0
- package/dist/permissions-CQW3cr2S.js +17 -0
- package/dist/permissions-DWULToSb.d.ts +52 -0
- package/dist/permissions-ijDw4sO1.js +144 -0
- package/dist/pg-CA651850.js +59 -0
- package/dist/pins-CXXkVEiD.js +14 -0
- package/dist/pipeline-CXuwijr2.js +307 -0
- package/dist/pkce-DdsRBK7n.js +20 -0
- package/dist/plugin-DGmbeXwA.d.ts +221 -0
- package/dist/plugin-MQVfUBUS.js +93 -0
- package/dist/plugin-outputs-BE2YCiMj.js +28 -0
- package/dist/policy-BhSUlHRr.js +37 -0
- package/dist/policy-C-Lzp3Zh.d.ts +18 -0
- package/dist/policy-DFD2J5o_.js +476 -0
- package/dist/policy-bundle-97xaDULc.js +82 -0
- package/dist/policy-from-catalog-YKaTeaco.js +452 -0
- package/dist/policy-module-Bp4HvsRg.js +107 -0
- package/dist/policy-types-93NwI8iI.d.ts +2855 -0
- package/dist/postgres-store-CYFvw98w.js +1023 -0
- package/dist/postgrest-DyrYo_XT.d.ts +138 -0
- package/dist/powersync-CN7IQIKk.js +40 -0
- package/dist/powersync-DdDLP02A.js +1630 -0
- package/dist/powersync-m9uYgCFF.js +1 -0
- package/dist/preset/index.d.ts +0 -12
- package/dist/preset/index.js +1 -1
- package/dist/preset-BcFDaeqd.js +1849 -0
- package/dist/principal-source-BIcukkB3.js +102 -0
- package/dist/prisma/index.d.ts +4 -12
- package/dist/prisma/index.js +10 -14
- package/dist/problem-BZB7zPC7.js +202 -0
- package/dist/problem-details-EJHcvYCz.js +154 -0
- package/dist/problem-types-81BEw0IN.js +7 -0
- package/dist/prompt-CSXHcJxy.js +931 -0
- package/dist/protected-action-BMb0ftEu.js +241 -0
- package/dist/protected-action-D6T3eJyW.d.ts +73 -0
- package/dist/protected-action-DiXulRVj.js +78 -0
- package/dist/provider-BnnFjtWI.js +893 -0
- package/dist/provider-ClD4rfgT.js +11 -0
- package/dist/provider-CydlnKkS.d.ts +4 -0
- package/dist/provider-store-atQUfsVO.js +51 -0
- package/dist/provider-with-CSw4mBDU.js +70 -0
- package/dist/public-api-DIMZmzWi.js +5579 -0
- package/dist/pull-9oQvY18T.js +252 -0
- package/dist/pull-jvJPMQhP.js +1 -0
- package/dist/push-Cb7PqXdO.js +158 -0
- package/dist/pushed-policy-pH-EFWyx.d.ts +61 -0
- package/dist/pushed-policy-rpB6k77P.js +240 -0
- package/dist/quote-BKrTBbcH.js +36 -0
- package/dist/rbac-B-49toAp.js +90 -0
- package/dist/react/index.d.ts +10 -9
- package/dist/react/index.js +8 -7
- package/dist/react/lazy.d.ts +10 -12
- package/dist/react/lazy.js +8 -35
- package/dist/react/provider-client-lazy.d.ts +2 -0
- package/dist/react/provider-client-lazy.js +2 -0
- package/dist/react/provider-client.d.ts +1 -1
- package/dist/react/provider-client.js +1 -1
- package/dist/react-native/index.d.ts +12 -30
- package/dist/react-native/index.js +31 -41
- package/dist/read-memberships-BkePIa1F.js +63 -0
- package/dist/refresh-on-C1zIMtJr.d.ts +47 -0
- package/dist/refresh-online-CYGZNo6V.js +19 -0
- package/dist/refresh-online-vtUfV6dk.d.ts +10 -0
- package/dist/refs-Cix9Zjis.js +103 -0
- package/dist/relation-walk-BlWy9gBK.js +188 -0
- package/dist/relations-CIgB5KPJ.js +162 -0
- package/dist/replay-ClGIMp5p.d.ts +3 -0
- package/dist/replay-X2m6moK1.js +28 -0
- package/dist/request-context-CVJodWx8.js +70 -0
- package/dist/request-context-E3-ps-H_.d.ts +3 -0
- package/dist/request-schema-DzEoR310.js +155 -0
- package/dist/resend/index.d.ts +4 -10
- package/dist/resend/index.js +14 -17
- package/dist/resolve-names-Cmg6SPAa.js +266 -0
- package/dist/resolver-kdZ4HrpC.js +404 -0
- package/dist/resource-ref-BiQtFK-I.js +19 -0
- package/dist/resource-relations-Ck5sjYQR.js +251 -0
- package/dist/retire-BNiXnbBR.js +248 -0
- package/dist/revocations-3jyzniOz.js +26 -0
- package/dist/revocations-ku_f2d2y.d.ts +24 -0
- package/dist/rls-BrsMogAP.js +321 -0
- package/dist/rls-Cv1V8YfI.js +946 -0
- package/dist/rls-files-Bj446vbj.js +114 -0
- package/dist/rls-options-Dpj_pEyU.d.ts +26 -0
- package/dist/role-builder-DhsGEVq-.js +501 -0
- package/dist/role-grants-Bk6ZsaS0.js +46 -0
- package/dist/roles-B29psCem.js +29 -0
- package/dist/rolldown-runtime-B8NLbhFH.js +3 -0
- package/dist/row-conditions-DwIJocfQ.js +27 -0
- package/dist/row-pair-CxEhErJU.js +33 -0
- package/dist/rpc-B-4IZOiU.js +111 -0
- package/dist/rpc-DjgxFbjK.d.ts +18 -0
- package/dist/run-DX4D6S6V.js +726 -0
- package/dist/run-decqEKNa.js +1 -0
- package/dist/run-ticket-D6T39Xdi.js +370 -0
- package/dist/run-ticket-DXwrko2J.d.ts +157 -0
- package/dist/runtime-Cl6xSbEq.js +13 -0
- package/dist/saas-DzjKUQr5.js +1218 -0
- package/dist/scan-Cj7PQLrS.js +28 -0
- package/dist/schema-BeY3croo.js +403 -0
- package/dist/schema-CJPvTfeN.js +133 -0
- package/dist/scim/index.d.ts +2 -2
- package/dist/scim/index.js +2 -2
- package/dist/scim-B9QyJ23q.js +1046 -0
- package/dist/scopes-B-KX9EI8.js +238 -0
- package/dist/seed-sql-CjF7u0aX.js +60 -0
- package/dist/seeds/index.d.ts +2 -0
- package/dist/seeds/index.js +1 -0
- package/dist/seeds-BDTG7xl-.js +53 -0
- package/dist/seeds-uG196Ev4.d.ts +73 -0
- package/dist/server/index.d.ts +13 -13
- package/dist/server/index.js +14 -14
- package/dist/server-Co9CYGqk.js +146 -0
- package/dist/server-types-BrHOGAYx.d.ts +318 -0
- package/dist/sha256-DFsnyVPo.js +157 -0
- package/dist/shared-BOsJIQf4.js +124 -0
- package/dist/shared-BdF5DJDQ.js +330 -0
- package/dist/signals-a1NxAP0X.js +31 -0
- package/dist/sink-BD34OS8T.d.ts +247 -0
- package/dist/sink-Bgvf9lIz.js +966 -0
- package/dist/size-DF7xQ-nH.js +95 -0
- package/dist/skills-B5bc6JIA.js +50 -0
- package/dist/skills-Cr1C0b9D.js +202 -0
- package/dist/snapshot-DckMnHk8.js +352 -0
- package/dist/snapshot-cache-DTTEfmxv.js +69 -0
- package/dist/snapshot-cache-DoP3avLl.d.ts +68 -0
- package/dist/snapshot-compact-CwAop_6C.js +119 -0
- package/dist/snapshot-empty-DZ6sZ83n.js +17 -0
- package/dist/snapshot-evaluate-9RGy7J3N.js +552 -0
- package/dist/snapshot-reads-D775amTL.js +65 -0
- package/dist/snapshot-size-D-pCR8x0.js +139 -0
- package/dist/snapshot-size-DU7CvpMt.js +1 -0
- package/dist/solid/index.d.ts +18 -20
- package/dist/solid/index.js +15 -19
- package/dist/solid-start/index.d.ts +6 -8
- package/dist/solid-start/index.js +4 -5
- package/dist/sources-BbSUNmFX.js +10 -0
- package/dist/sources-DnjJPGfb.js +657 -0
- package/dist/sources-NQio1yFq.d.ts +727 -0
- package/dist/sql-BYYNi1lu.d.ts +8 -0
- package/dist/sql-T4GaBh9X.js +93 -0
- package/dist/src-D6_T4zd7.js +1811 -0
- package/dist/ssf/index.d.ts +3 -3
- package/dist/ssf/index.js +20 -31
- package/dist/standard-webhooks-B3MQihcP.d.ts +86 -0
- package/dist/standard-webhooks-BtIkXclH.js +227 -0
- package/dist/storage-BhGDhsXm.js +131 -0
- package/dist/store-AH8bmaxW.js +377 -0
- package/dist/store-core-eqG8jijs.d.ts +306 -0
- package/dist/store-options-C8x39AHa.js +1034 -0
- package/dist/stores-4DOaL4ZP.d.ts +58 -0
- package/dist/stores-DoA7ACkz.js +127 -0
- package/dist/stream-DdF94h7T.js +73 -0
- package/dist/style-CQDaLJtP.js +24 -0
- package/dist/style-Crf-90o6.js +1 -0
- package/dist/subject-DkxY-AhF.js +23 -0
- package/dist/subject-cache-BZeSj4Xf.d.ts +156 -0
- package/dist/subject-settings-BO-frcYx.js +147 -0
- package/dist/subject-settings-C9F1sU1d.d.ts +48 -0
- package/dist/supabase/client.d.ts +1 -1
- package/dist/supabase/client.js +2 -3
- package/dist/supabase/index.d.ts +77 -24
- package/dist/supabase/index.js +9 -8
- package/dist/supabase/middleware.d.ts +27 -9
- package/dist/supabase/middleware.js +51 -21
- package/dist/supabase-BG1HPdQU.js +30 -0
- package/dist/supabase-BI5ZhzLl.js +792 -0
- package/dist/supabase-config-mXcggV5I.js +890 -0
- package/dist/supabase-hook-hd9abKy4.js +2 -0
- package/dist/supabase-hook-tdR45aXY.js +405 -0
- package/dist/supabase-outcome-CMLuLW-V.js +9 -0
- package/dist/supautils-DXzJ2E2Q.js +96 -0
- package/dist/support-session-B8xrW28B.js +157 -0
- package/dist/svelte/index.d.ts +8 -10
- package/dist/svelte/index.js +12 -15
- package/dist/svelte/runtime.d.ts +4 -6
- package/dist/svelte/runtime.js +4 -4
- package/dist/svelte/source.d.ts +8 -10
- package/dist/svelte/source.js +6 -7
- package/dist/sveltekit/index.d.ts +6 -8
- package/dist/sveltekit/index.js +3 -4
- package/dist/tables-CRTCBuFi.js +3240 -0
- package/dist/tanstack-start/index.d.ts +6 -8
- package/dist/tanstack-start/index.js +3 -4
- package/dist/target-BGpxgKsN.js +50 -0
- package/dist/tenancy-B5Xxt9Sc.js +223 -0
- package/dist/terminal/index.d.ts +6 -16
- package/dist/terminal/index.js +18 -23
- package/dist/testing/core.d.ts +1 -1
- package/dist/testing/core.js +1 -1
- package/dist/testing/fixtures/index.d.ts +12 -10
- package/dist/testing/fixtures/index.js +48 -25
- package/dist/testing/index.d.ts +85 -85
- package/dist/testing/index.js +226 -115
- package/dist/testing/saas/index.d.ts +5 -15
- package/dist/testing/saas/index.js +2 -2
- package/dist/testing/saas/permissions.d.ts +1 -1
- package/dist/testing/saas/permissions.js +1 -1
- package/dist/text-D704xHVl.js +7 -0
- package/dist/text-diff-CsglY49A.js +440 -0
- package/dist/thenable-BxMy2v8w.js +39 -0
- package/dist/time-r0CKBm57.js +94 -0
- package/dist/timeout-nOqLpU2I.js +7 -0
- package/dist/token-BgswTQzt.d.ts +9 -0
- package/dist/token-CSljQqzA.js +76 -0
- package/dist/tool-refusal-DzCSbjp8.js +43 -0
- package/dist/trpc/index.d.ts +7 -9
- package/dist/trpc/index.js +7 -8
- package/dist/type-helpers-DHCQEPj8.d.ts +47 -0
- package/dist/types-3pRMqcvw.d.ts +84 -0
- package/dist/types-BFtFaI1W.d.ts +66 -0
- package/dist/types-BdNdMix7.d.ts +263 -0
- package/dist/types-C7QtRn3n.d.ts +66 -0
- package/dist/types-CVCRFYY_.d.ts +102 -0
- package/dist/types-CWmBZtQN.d.ts +274 -0
- package/dist/types-Cakw89Wx.d.ts +372 -0
- package/dist/types-D3tjoLwT.d.ts +124 -0
- package/dist/types-D8VXQxKL.d.ts +1231 -0
- package/dist/types-DFZKovb3.js +77 -0
- package/dist/types-DONLJQjY.d.ts +134 -0
- package/dist/types-OzSal_K_.d.ts +178 -0
- package/dist/types-XSfi6ihL.d.ts +65 -0
- package/dist/unplugin/index.d.ts +1 -3
- package/dist/unplugin/index.js +3 -4
- package/dist/usage-B-E747wO.js +31 -0
- package/dist/usage-B7nx0_aa.js +761 -0
- package/dist/usage-rqQ9ViXv.js +1 -0
- package/dist/validation-error-BAO1W1yk.d.ts +27 -0
- package/dist/validation-error-CgDOA6VS.js +35 -0
- package/dist/validity-YNEEm2MZ.js +56 -0
- package/dist/verifier-BIYkGcJc.js +530 -0
- package/dist/verify-9HObfifg.js +1102 -0
- package/dist/version-CU6e2wxV.js +7 -0
- package/dist/version-D-jWyJb9.js +46 -0
- package/dist/version-DcZCjWXb.js +1 -0
- package/dist/version-cache-BXkl7-Fz.js +462 -0
- package/dist/views-Dpr1uB16.js +164 -0
- package/dist/vocabulary-CE2k7s1a.js +157 -0
- package/dist/vocabulary-FYgI_NoI.d.ts +400 -0
- package/dist/vue/index.d.ts +18 -20
- package/dist/vue/index.js +13 -18
- package/dist/waiter-DKdFHKVZ.js +66 -0
- package/dist/waiter-hYLJXA7r.d.ts +37 -0
- package/dist/watch-BecZtEdU.js +155 -0
- package/dist/watch-CiN6WU9k.js +221 -0
- package/dist/watch-NAUnUXph.js +1 -0
- package/dist/webmcp/index.d.ts +2 -6
- package/dist/webmcp/index.js +8 -9
- package/dist/who-can-rUSZfLvI.js +366 -0
- package/dist/wire-delegation-DC5Cyec4.js +35 -0
- package/dist/wire-denial-BcRQnA7p.js +26 -0
- package/dist/workflow/index.d.ts +3 -3
- package/dist/workflow/index.js +12 -14
- package/dist/workflow-sdk/index.d.ts +6 -8
- package/dist/workflow-sdk/index.js +2 -3
- package/dist/wrap-CsfsaJhd.js +32 -0
- package/dist/wrap-D-KvhzaC.d.ts +16 -0
- package/package.json +83 -39
- package/schemas/catalog-v2.json +665 -0
- package/schemas/cli-commands-v1.json +1 -1
- package/schemas/cli-result-v2.json +163 -0
- package/schemas/cloud-api-v1.json +1 -1
- package/schemas/snapshot-v1.json +26 -0
- package/schemas/supabase-claims-v1.json +5 -1
- package/schemas/supabase-manifest-v1.json +11 -2
- package/skills/permdock/SKILL.md +1 -1
- package/skills/permdock-data/references/queries-and-rls.md +2 -1
- package/skills/permdock-wire/references/adapters.md +5 -3
- package/dist/2020-CJbO8Bvz.js +0 -6773
- package/dist/active-tenant-DVee32-T.js +0 -39
- package/dist/adapter-context-OHikyRqV.js +0 -29
- package/dist/adoption-scan-DhZejKH8.js +0 -107
- package/dist/app-J9PE1LNm.js +0 -24
- package/dist/app-data-UNNm07jV.js +0 -63
- package/dist/approval-header-8QV6MU4H.js +0 -26
- package/dist/approval-normalize-KfhzpD93.js +0 -196
- package/dist/approval-policies-BiXMlYBu.d.ts +0 -138
- package/dist/approval-prompt-B8hQY69x.js +0 -61
- package/dist/approval-prompt-j5PTItiy.d.ts +0 -59
- package/dist/approval-required-TzNB9oQA.js +0 -6
- package/dist/approvals-BfzI8Foe.js +0 -1048
- package/dist/approvers-BaNwKYgd.js +0 -77
- package/dist/arazzo-2_9pOddr.js +0 -77
- package/dist/arazzo-BDDzHgwW.js +0 -36
- package/dist/args-iafbHiXn.js +0 -311
- package/dist/audience-DLoopY4q.js +0 -55
- package/dist/auth-BxXHxWRy.js +0 -189
- package/dist/authz-topic-Dbc-HDOS.js +0 -15
- package/dist/automation-BueW05db.js +0 -158
- package/dist/automation-_iGeP54L.d.ts +0 -124
- package/dist/base-url-BQbddZO5.js +0 -9
- package/dist/better-supabase-DF8f8oly.js +0 -194
- package/dist/bind-CTj4dHc1.d.ts +0 -58
- package/dist/bind-LQ6zbARV.js +0 -125
- package/dist/body-Cy9S8zhw.js +0 -10
- package/dist/body-text-DQhcmqdY.js +0 -56
- package/dist/boundary-BV3O1eud.js +0 -19
- package/dist/boundary-C9ck-3uK.d.ts +0 -24
- package/dist/budget-BBCPDOGP.js +0 -14
- package/dist/budget-CNLsV2SL.d.ts +0 -14
- package/dist/build-instance-Bq8wkJ4i.js +0 -31
- package/dist/canonical-json-DwilZ1iB.js +0 -29
- package/dist/capability-CenWwTMR.js +0 -205
- package/dist/capability-DqCyFGip.d.ts +0 -130
- package/dist/casbin-BspH3-6_.js +0 -30
- package/dist/casbin-XFqehd6I.js +0 -242
- package/dist/casl-CjBVJj8R.js +0 -24
- package/dist/casl-CkBssiB1.js +0 -308
- package/dist/catalog-B1MAmRQI.js +0 -131
- package/dist/catalog-BCVIH7kq.js +0 -1
- package/dist/catalog-CaZoXBD8.js +0 -52
- package/dist/catalog-doc-DnQDviXY.js +0 -353
- package/dist/catalog-fingerprint-e6aCWosn.js +0 -157
- package/dist/catalog-operations-Do1eD-Rt.js +0 -60
- package/dist/catalog-path-CnI0XTFK.js +0 -12
- package/dist/challenge-DKJpP-5P.js +0 -521
- package/dist/checks-fyDOhcz0.js +0 -72
- package/dist/claims-map-CKkoAAYF.js +0 -16
- package/dist/claims-map-D1Pb5oRq.d.ts +0 -35
- package/dist/client-JK504UCq.d.ts +0 -45
- package/dist/clients-C_NOET3z.d.ts +0 -12
- package/dist/clients-DYr3U86j.js +0 -23
- package/dist/cloud-CUvR7okV.js +0 -86
- package/dist/codemod-iwXnO0fg.js +0 -2800
- package/dist/codemod-uZsk1b6T.js +0 -36
- package/dist/collect-BG-SXFQv.js +0 -537
- package/dist/collect-CxPJRjoc.js +0 -55
- package/dist/collect-ZLgHgujd.js +0 -1
- package/dist/command-L8EstFNm.js +0 -6
- package/dist/compact-CAf557ZB.js +0 -29
- package/dist/compare-DTfyUunF.js +0 -12
- package/dist/compile-Cvru58id.js +0 -661
- package/dist/compile-Dh9pW_Co.d.ts +0 -120
- package/dist/completion-DenWMczI.js +0 -152
- package/dist/config-CoUYTCCu.js +0 -26
- package/dist/config-DC7aiuhP.js +0 -116
- package/dist/config-report-C5D1rPiF.js +0 -56
- package/dist/config-shape-ChhsuGSV.js +0 -147
- package/dist/connection-zoAgwdsD.js +0 -197
- package/dist/connector-schema-CYLQNMYq.js +0 -434
- package/dist/constants-DcJABbLW.js +0 -20
- package/dist/context-BXM0MDB0.js +0 -95
- package/dist/core-BTJlqWsv.js +0 -341
- package/dist/core-BhZEo5Le.d.ts +0 -206
- package/dist/coverage-BuGlwUms.d.ts +0 -135
- package/dist/coverage-CGu_Kovx.js +0 -261
- package/dist/create--q7-j0hX.d.ts +0 -127
- package/dist/create-C5IQw_-i.d.ts +0 -191
- package/dist/create-CYj0cjTu.d.ts +0 -128
- package/dist/create-D7D94oNh.js +0 -376
- package/dist/create-DaddhCIg.js +0 -134
- package/dist/credential-BMsbcaeP.js +0 -431
- package/dist/credentials-BZU7Twpt.js +0 -310
- package/dist/credentials-Bq-Xa7Vq.d.ts +0 -125
- package/dist/credentials-dkycUsY3.js +0 -74
- package/dist/decide-set-DXEPepY1.js +0 -100
- package/dist/deciding-columns-NB4wcyBf.js +0 -134
- package/dist/decision-CaG5_eNJ.js +0 -21
- package/dist/delegation-CrdqnesZ.js +0 -262
- package/dist/delegation-input-DcXhiMkf.js +0 -19
- package/dist/delivery-BupfvJIV.js +0 -560
- package/dist/delivery-event-JioK5YbS.js +0 -40
- package/dist/denied-text-B6s29jcf.d.ts +0 -22
- package/dist/describe-BZAlPHxT.js +0 -101
- package/dist/describe-DwcoWMLB.d.ts +0 -45
- package/dist/device-BkSynWdg.js +0 -196
- package/dist/diff-BnYHpRSI.js +0 -466
- package/dist/diff-H75YU6Q-.js +0 -37
- package/dist/digest-8Yx2CchM.d.ts +0 -19
- package/dist/digest-BI-6aa6d.js +0 -27
- package/dist/doctor-CF9TXVkX.js +0 -3560
- package/dist/doctor-DreyO1At.js +0 -54
- package/dist/env-DJZrPjRi.js +0 -8
- package/dist/errors-BDUwg2qC.js +0 -27
- package/dist/errors-BhRkoNS7.js +0 -145
- package/dist/errors-CHwoRRpB.d.ts +0 -14
- package/dist/errors-D_SnqcRn.d.ts +0 -141
- package/dist/errors-ynga1EQy.js +0 -128
- package/dist/evaluate-BQ2nWOki.js +0 -1905
- package/dist/evaluations-BVtY66lF.d.ts +0 -38
- package/dist/evaluations-Bj5xw0EM.js +0 -612
- package/dist/evaluator-CDl2YUd_.js +0 -2
- package/dist/evaluator-eager-CULtQ8t6.js +0 -9
- package/dist/event-time-BGy48400.js +0 -27
- package/dist/fetch-adapter-BJ76IZZg.d.ts +0 -34
- package/dist/fetch-adapter-CXeBg4CH.js +0 -124
- package/dist/fields-D9PIYlJy.js +0 -504
- package/dist/fields-DlKwZYiy.js +0 -26
- package/dist/files-BSjrtIHw.js +0 -141
- package/dist/files-CfiRtQ-m.js +0 -140
- package/dist/fixtures-BVZc7OCF.js +0 -80
- package/dist/flags-BlmpmXoY.js +0 -86
- package/dist/freeze-jjan0lCv.js +0 -63
- package/dist/from-snapshot-FdVXG_QZ.js +0 -159
- package/dist/gen-BU5glz2Q.js +0 -827
- package/dist/gen-C75KIBdA.js +0 -58
- package/dist/generate-BqkZq8Dr.js +0 -165
- package/dist/generate-CezbCaTI.js +0 -275
- package/dist/grantee-OG4klcNr.js +0 -110
- package/dist/grantee-conditions-Dzprappv.js +0 -271
- package/dist/grantee-match-CPQ9zV-H.js +0 -148
- package/dist/graph-sql-BwFC4Qjs.d.ts +0 -29
- package/dist/headers-B9jQxjtW.d.ts +0 -10
- package/dist/helpers-CO2hDpBU.js +0 -537
- package/dist/hosted-CQW_YNx7.js +0 -362
- package/dist/hosted-D5StFpKa.d.ts +0 -102
- package/dist/http-B_LphE5Y.d.ts +0 -12
- package/dist/http-DH94eh6f.js +0 -72
- package/dist/http-DKLXrFGk.js +0 -83
- package/dist/http-dptLQzPP.js +0 -49
- package/dist/ids-DzhJaCUj.js +0 -55
- package/dist/import-B34PyXgL.js +0 -5950
- package/dist/import-BYYXmHvP.js +0 -1143
- package/dist/index-B1-tE0Kx.d.ts +0 -1159
- package/dist/index-BwSEp_O5.d.ts +0 -210
- package/dist/index-CB_eM-qx.d.ts +0 -101
- package/dist/index-CvcE9mYP.d.ts +0 -234
- package/dist/index-D7sMtTf6.d.ts +0 -542
- package/dist/index-d7f0hNss.d.ts +0 -233
- package/dist/init-C-nzibt_.js +0 -96
- package/dist/init-C1Bj0BFA.js +0 -95
- package/dist/instance-options-DhQVCuhT.d.ts +0 -11
- package/dist/instance-options-URVwqpMW.js +0 -24
- package/dist/instance-snapshot-DyG_5ASl.js +0 -693
- package/dist/instant-DK3Iz83e.js +0 -19
- package/dist/internals-B3IgHrvo.js +0 -20
- package/dist/json-schema-BPGa-RjQ.js +0 -149
- package/dist/json-schema-BfXgnRNT.d.ts +0 -40
- package/dist/kernel-D9AxUqmz.js +0 -427
- package/dist/limits-CAhpRrhk.js +0 -167
- package/dist/live-options-BBIT68le.js +0 -73
- package/dist/load-C4p4VgwR.js +0 -99
- package/dist/load-DiBUJx77.js +0 -1
- package/dist/load-jose-DZ4dnjri.js +0 -8
- package/dist/login-Cm_ebe5M.js +0 -68
- package/dist/login-DjuUQqqK.js +0 -257
- package/dist/lru-8q4WZjBV.js +0 -28
- package/dist/manifest-9KSrH_1h.js +0 -401
- package/dist/manifest-BoCYBbQL.js +0 -46
- package/dist/manifest-C6eFl3Vo.d.ts +0 -349
- package/dist/manifest-json-CAGzls-C.js +0 -9
- package/dist/manifest-schema-svAkgqMc.js +0 -501
- package/dist/map-claims-CAa_bQt9.js +0 -387
- package/dist/map-error-BCdb2Nrp.js +0 -23
- package/dist/markers-BeHZ4x9Q.js +0 -80
- package/dist/may-use-WDhFPqGG.js +0 -125
- package/dist/membership-filter-BWnfRQzo.js +0 -68
- package/dist/migrate-DVsxeE0y.js +0 -537
- package/dist/module-values-CdaVwrab.js +0 -107
- package/dist/oauth-security-X7Em8DbH.js +0 -26
- package/dist/ocsf-TcjRBgIs.js +0 -136
- package/dist/openapi-C2WGtmFa.js +0 -137
- package/dist/openapi-Cc-aS9xC.js +0 -416
- package/dist/openapi-DvTtFkwY.js +0 -256
- package/dist/operation-findings-CVwJHEu_.js +0 -36
- package/dist/operation-risks-BKOcTv8J.js +0 -13
- package/dist/operations-BMPx7HyO.d.ts +0 -62
- package/dist/operations-Bm9HFecz.js +0 -89
- package/dist/optional-8TKc-0j4.js +0 -47
- package/dist/output-CuJfGWo6.js +0 -96
- package/dist/output-files-BYscrQl-.js +0 -1
- package/dist/output-files-CM0BnH05.js +0 -150
- package/dist/ownership-C_5eZ6N2.js +0 -1062
- package/dist/parse-CORUNcCo.js +0 -151
- package/dist/parse-local-manifest-Ce2N-Opr.js +0 -69
- package/dist/parse-local-manifest-w_ksIkB9.d.ts +0 -10
- package/dist/parse-request-DOBVaeiQ.js +0 -25
- package/dist/paths-CUvURzHp.js +0 -45
- package/dist/peer-BuK9F53f.js +0 -982
- package/dist/peer-n-swIV4H.js +0 -1
- package/dist/permdock-B3zE16To.js +0 -1203
- package/dist/permdock-DV3opaI3.d.ts +0 -674
- package/dist/permission-registry-B8tYxPIt.js +0 -398
- package/dist/permissions-BaoLxy66.js +0 -18
- package/dist/permissions-D-M48hW-.js +0 -146
- package/dist/permissions-DriWkV7q.d.ts +0 -54
- package/dist/pg-Ddxsd5ZB.js +0 -60
- package/dist/pins-nqarl3oE.js +0 -15
- package/dist/pkce-CnmmYqUZ.js +0 -21
- package/dist/policy-DIHfTqm6.d.ts +0 -20
- package/dist/policy-DnNOTENd.js +0 -430
- package/dist/policy-from-catalog-Z0hvSffr.js +0 -454
- package/dist/policy-module-xym9fnSq.js +0 -95
- package/dist/policy-types-DU389Elz.d.ts +0 -2809
- package/dist/postgres-store-DcyrPS-r.js +0 -1028
- package/dist/postgrest-3dE9SGx9.d.ts +0 -124
- package/dist/powersync-BO1ty3Mf.js +0 -1
- package/dist/powersync-Bqy5Un2J.js +0 -1532
- package/dist/powersync-CCQAqiOo.js +0 -62
- package/dist/preset-Bn5Z54cH.js +0 -1858
- package/dist/principal-source-C6N60GtM.js +0 -103
- package/dist/problem-CPB8kqk7.js +0 -203
- package/dist/problem-details-CLDgX1KV.js +0 -156
- package/dist/problem-types-DSsRfONQ.js +0 -8
- package/dist/prompt-D1Gj1W4Y.js +0 -938
- package/dist/protected-action-CjSUoPGx.d.ts +0 -76
- package/dist/protected-action-D41o5LvP.js +0 -244
- package/dist/protected-action-OpOxtTsN.js +0 -80
- package/dist/provider-Bzzux0TR.js +0 -12
- package/dist/provider-D1jsNJ85.d.ts +0 -6
- package/dist/provider-store-tIAwP4aW.js +0 -52
- package/dist/provider-with-Do28DhxP.js +0 -69
- package/dist/pull-CYdd5HzX.js +0 -1
- package/dist/pull-DLkaZBwH.js +0 -257
- package/dist/push-sJ5dy46a.js +0 -162
- package/dist/pushed-policy-Db651nih.d.ts +0 -63
- package/dist/pushed-policy-UZyQinrL.js +0 -241
- package/dist/refresh-on-L9UOwATg.d.ts +0 -49
- package/dist/refs-C8BKxc_e.js +0 -105
- package/dist/relation-walk-BDTaTKTM.js +0 -189
- package/dist/relations-CMsJ1ARY.js +0 -163
- package/dist/replay-BU09ad4L.js +0 -29
- package/dist/replay-BpmpY2ev.d.ts +0 -5
- package/dist/request-context-C2_1lchh.d.ts +0 -5
- package/dist/request-context-dyCY4V1t.js +0 -71
- package/dist/request-schema-CMP8Cmxd.js +0 -156
- package/dist/resolve-names-DHDedxk0.js +0 -206
- package/dist/resource-ref-CaS9yVPi.js +0 -20
- package/dist/resource-relations-8-pCScBO.js +0 -252
- package/dist/retire-B2xffQgY.js +0 -249
- package/dist/revocations-BaUXHM1N.d.ts +0 -26
- package/dist/revocations-Bhr0aMIC.js +0 -27
- package/dist/rls-B3-tGA4r.js +0 -2700
- package/dist/rls-BW2u4lQW.js +0 -367
- package/dist/role-builder-BXdhhQcB.js +0 -507
- package/dist/rolldown-runtime-C3I60J0A.js +0 -4
- package/dist/row-conditions-BAGHOmVq.js +0 -28
- package/dist/row-pair-DglMdRFh.js +0 -34
- package/dist/rpc-BdFGYcWm.js +0 -112
- package/dist/rpc-DKRQobOX.d.ts +0 -22
- package/dist/run-2GwcSago.js +0 -694
- package/dist/run-CdGNonHf.js +0 -1
- package/dist/run-ticket-Ddxt9OuU.js +0 -371
- package/dist/run-ticket-o4RxoaEN.d.ts +0 -159
- package/dist/runtime-rf0ZuyF3.js +0 -14
- package/dist/saas-D9maBt0q.js +0 -1223
- package/dist/scan-CB46GDQ0.js +0 -29
- package/dist/schema-BlnU_TzE.js +0 -414
- package/dist/schema-CyEB_zeO.js +0 -134
- package/dist/scim-BG6uPUeW.js +0 -1056
- package/dist/scim-CovliQUg.js +0 -44
- package/dist/scopes-gdH__vDZ.js +0 -239
- package/dist/server-CKjFooaJ.js +0 -147
- package/dist/server-types-C4q8_8MM.d.ts +0 -325
- package/dist/sha256-C-4WXKIu.js +0 -158
- package/dist/shared-BRmCJxDK.js +0 -125
- package/dist/shared-DfaIWvIJ.js +0 -354
- package/dist/signals-B1vHR3fN.js +0 -32
- package/dist/sink-C3KDccl9.d.ts +0 -249
- package/dist/sink-D9_vh372.js +0 -968
- package/dist/skills-BYHCObpD.js +0 -51
- package/dist/skills-C-9wjNaE.js +0 -204
- package/dist/snapshot-D0VOanxQ.js +0 -334
- package/dist/snapshot-cache-B66h7FBK.js +0 -70
- package/dist/snapshot-cache-C1mN0pXe.d.ts +0 -70
- package/dist/snapshot-compact-CUtXsx6i.js +0 -75
- package/dist/snapshot-empty-F7d5BRlc.js +0 -18
- package/dist/snapshot-evaluate-C3ZA35O_.js +0 -501
- package/dist/snapshot-reads-CNNmp1cK.js +0 -66
- package/dist/sources-2virTxHt.d.ts +0 -721
- package/dist/sources-C4vkzZJV.js +0 -660
- package/dist/sources-qoIJQrJv.js +0 -11
- package/dist/sql-0WjxIp9g.js +0 -80
- package/dist/sql-B80DFdpG.d.ts +0 -10
- package/dist/src-ieIv22BA.js +0 -2080
- package/dist/standard-webhooks-B2g_yWK8.d.ts +0 -88
- package/dist/standard-webhooks-D67a3nzk.js +0 -228
- package/dist/storage-C2bWdvJH.js +0 -132
- package/dist/store-DXO0aVgf.js +0 -380
- package/dist/store-core-BI-9ZU-5.d.ts +0 -311
- package/dist/store-options-BYKNX_JG.js +0 -993
- package/dist/stores-DtM8pt8o.js +0 -128
- package/dist/stores-DwGfIcmq.d.ts +0 -57
- package/dist/stream-DQ3rbO3J.js +0 -74
- package/dist/style-DblOtSga.js +0 -1
- package/dist/style-Ds11Hmk4.js +0 -25
- package/dist/subject-C7RddW0G.js +0 -24
- package/dist/subject-cache-BT1fGuea.js +0 -193
- package/dist/subject-cache-TY2tw-k9.d.ts +0 -144
- package/dist/subject-jG6o8eKo.js +0 -556
- package/dist/subject-settings-8sH5HlII.js +0 -150
- package/dist/subject-settings-vNW8qmUH.d.ts +0 -52
- package/dist/supabase-BlAqmxD8.js +0 -723
- package/dist/supabase-C1hExXsZ.js +0 -92
- package/dist/supabase-hook-DCemge7i.js +0 -1
- package/dist/supabase-hook-DJA8AJYz.js +0 -4263
- package/dist/supautils-DuwkBqKm.js +0 -1186
- package/dist/support-session-BGeEYDSq.js +0 -158
- package/dist/tables-B3w3EtUF.js +0 -4002
- package/dist/target-qdEAnnhU.js +0 -51
- package/dist/tenancy-BlxY5T0q.js +0 -224
- package/dist/text-BMFRfBqc.js +0 -8
- package/dist/text-diff-BtfSmdUo.js +0 -444
- package/dist/thenable-BNSM1U2R.js +0 -40
- package/dist/time-nR1JesoH.js +0 -95
- package/dist/timeout-D51niuQP.js +0 -8
- package/dist/token-D6pWn8Uj.d.ts +0 -11
- package/dist/token-DaMnIU9O.js +0 -77
- package/dist/tool-refusal-D4spOJ7I.js +0 -44
- package/dist/type-helpers-tDoGEIsd.d.ts +0 -49
- package/dist/types-61f3KMtI.d.ts +0 -1136
- package/dist/types-BDgMzK1i.d.ts +0 -368
- package/dist/types-BIvkpVoc.d.ts +0 -180
- package/dist/types-BWjNPQkS.d.ts +0 -67
- package/dist/types-Bq4AU68k.d.ts +0 -105
- package/dist/types-BsqLNNvG.d.ts +0 -68
- package/dist/types-CH67RMvL.d.ts +0 -136
- package/dist/types-CcUXciSj.js +0 -79
- package/dist/types-DAyp592k.d.ts +0 -276
- package/dist/types-DEDocm4c.d.ts +0 -81
- package/dist/types-DQQkzF97.d.ts +0 -126
- package/dist/types-DdeivUBP.d.ts +0 -68
- package/dist/types-X40XNxRP.d.ts +0 -265
- package/dist/usage-BBEm7GVn.js +0 -762
- package/dist/usage-CkKbvpmL.js +0 -32
- package/dist/usage-GQxn7qkA.js +0 -1
- package/dist/validation-error-CV0nV6_L.d.ts +0 -29
- package/dist/validation-error-CYg2kJEw.js +0 -36
- package/dist/validity-IcjQSR7I.js +0 -57
- package/dist/verifier-DUV6pLqZ.js +0 -519
- package/dist/verify-lgYu1Twv.js +0 -1736
- package/dist/version-DMQ0dnN5.js +0 -48
- package/dist/version-DizhmD72.js +0 -1
- package/dist/version-sources-BRb9ZteH.js +0 -34
- package/dist/views-MWmJ6Y4P.js +0 -147
- package/dist/vocabulary-BuYFWeCU.js +0 -158
- package/dist/vocabulary-DeZvUaTw.d.ts +0 -401
- package/dist/waiter-BophA4BT.d.ts +0 -39
- package/dist/waiter-aBLM63_f.js +0 -67
- package/dist/watch-CJKYQYNb.js +0 -167
- package/dist/watch-Cv-xvI6e.js +0 -1
- package/dist/who-can-Yh9WdiwK.js +0 -367
- package/dist/wire-delegation-Cv3W2eaM.js +0 -36
- package/dist/wire-denial-C7PaVYEM.js +0 -27
- package/dist/wrap-Bq9fHwuT.d.ts +0 -18
- package/dist/wrap-C5PWzgkq.js +0 -33
- package/schemas/catalog-v1.json +0 -679
- package/schemas/cli-result-v1.json +0 -95
|
@@ -0,0 +1,3240 @@
|
|
|
1
|
+
import { c as listPermissions, h as formerKeys } from "./permission-registry-DMYRZVcn.js";
|
|
2
|
+
import { a as expandRelation, c as isEdgeRelation, d as isSelfParented, l as isFieldRelation, o as groupEntries, p as restrictedFor, u as isPrincipalRelation } from "./resource-relations-Ck5sjYQR.js";
|
|
3
|
+
import { o as flattenGrantee } from "./grantee-BPUG6f0r.js";
|
|
4
|
+
import { c as rootScope, d as scopeList } from "./scopes-B-KX9EI8.js";
|
|
5
|
+
import { t as canonicalJson } from "./canonical-json-BibZkXtE.js";
|
|
6
|
+
import { r as relationCondition, t as inheritCondition } from "./grantee-conditions-Dob6QQAc.js";
|
|
7
|
+
import { l as partitionsOf, p as scopeField } from "./tenancy-B5Xxt9Sc.js";
|
|
8
|
+
import { a as delegatedScopeMap } from "./permdock-BueSeg7X.js";
|
|
9
|
+
import { i as configError } from "./errors-DgLOqc6j.js";
|
|
10
|
+
import { d as sqlTextArray, i as qualifySqlTable, t as SQL_IDENT } from "./sql-T4GaBh9X.js";
|
|
11
|
+
import { d as restrictedRowsSql, i as scopeColumn, l as relationArmSql } from "./compile-BUKXrueE.js";
|
|
12
|
+
import { t as AUTHZ_VERSION_TABLE } from "./sources-DnjJPGfb.js";
|
|
13
|
+
import { a as quoteIdent, c as quoteTable, i as qualified, o as quoteLiteral, r as helperSchema, s as quoteQualified } from "./quote-BKrTBbcH.js";
|
|
14
|
+
import { A as tenantTypeOf, D as idTypeOf, O as scopeTypeOf, _ as subjectClaimJsonSql, d as keyTenantSql, f as kindFilterSql, h as roleKindSql, i as allowEntry, m as memberVia, n as GLOBAL_ROLES, o as rootName, r as HELPERS, s as signedIn, t as CUSTOM_ROLES, v as subjectClaimSql, x as userIdHelperSql, y as subjectIdSql } from "./shared-BdF5DJDQ.js";
|
|
15
|
+
import { $ as linkHelper, A as userActive, B as trustedReaderGrants, C as sourcesKeep, D as keyTenantLine, E as instancesActive, F as perScope, G as graphHelper, H as byKey, I as raiseSql, J as hasMemberFor, K as graphSqlName, L as roleReadersSql, M as currentKeyExpr, N as customRolesSql, P as hasCustomRoleChecksFor, Q as isTeamScope, R as rolesTableScope, S as sourcesBodyOf, V as byCodeUnit, W as CLOSURE, Y as hasMemberOf, _ as memoizes, at as memberRoleOf, b as sourceIdOf, c as claimTenant, ct as restrictedHelper, d as hasBody, dt as activeInstancesSql, et as memberForHelper, ft as activeMembershipSql, g as memoizedSetofSql, gt as grantPermissionSql, h as memoWriteSql, it as memberOfHelper, j as globalRoleSource, l as disabledColumn, lt as scopeSources, m as memoHitList, mt as activeUserSql, n as interactiveAllowsCall, o as memoUserSql, ot as permittedForHelper, p as memberColumn, pt as activeRowSql, q as graphSqlText, r as interactiveAllowsSql, rt as memberIdsHelper, s as claimKeptLines, st as permittedIdsHelper, tt as memberForSources, u as functionBody, ut as scopeTable, v as scopedBody, w as sqlBody, x as sourceRows, y as sourceFilters, z as storedTenant } from "./interactive-only-BZu9rLpa.js";
|
|
16
|
+
import { createHash } from "node:crypto";
|
|
17
|
+
// src/cli/rls/graph.ts
|
|
18
|
+
function tableFor(resource, tables) {
|
|
19
|
+
return tables?.[resource] ?? resource;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Every `related` condition the policy's grants compile to, with the resource
|
|
23
|
+
* graph they need, groups included.
|
|
24
|
+
*/
|
|
25
|
+
function graphPlan(policy) {
|
|
26
|
+
const scopes = scopeList(policy.scopes);
|
|
27
|
+
const plan = /* @__PURE__ */ new Map();
|
|
28
|
+
const entryFor = (node) => {
|
|
29
|
+
const entry = plan.get(node.name) ?? {
|
|
30
|
+
node,
|
|
31
|
+
relations: /* @__PURE__ */ new Set(),
|
|
32
|
+
links: /* @__PURE__ */ new Set()
|
|
33
|
+
};
|
|
34
|
+
plan.set(node.name, entry);
|
|
35
|
+
return entry;
|
|
36
|
+
};
|
|
37
|
+
const addRelation = (node, relation) => {
|
|
38
|
+
const entry = entryFor(node);
|
|
39
|
+
if (entry.relations.has(relation)) return;
|
|
40
|
+
entry.relations.add(relation);
|
|
41
|
+
for (const name of expandRelation(node, relation)) {
|
|
42
|
+
const spec = node.relations[name];
|
|
43
|
+
if (!isEdgeRelation(spec) || spec.groups === void 0) continue;
|
|
44
|
+
for (const { resource, relation: groupRelation } of groupEntries(spec)) {
|
|
45
|
+
const target = policy.resources.get(resource);
|
|
46
|
+
if (target !== void 0 && target.name !== node.name) addRelation(target, groupRelation);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
const addLinks = (hops) => {
|
|
51
|
+
for (let index = 1; index < hops.length; index += 1) {
|
|
52
|
+
const from = policy.resources.get(hops[index - 1]?.resource ?? "");
|
|
53
|
+
const hop = hops[index];
|
|
54
|
+
if (from !== void 0 && hop !== void 0) entryFor(from).links.add(hop.link);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
const addAbove = (above) => {
|
|
58
|
+
const node = above === void 0 ? void 0 : policy.resources.get(above.resource);
|
|
59
|
+
if (above === void 0 || node === void 0) return;
|
|
60
|
+
const entry = entryFor(node);
|
|
61
|
+
entry.closure = Math.max(entry.closure ?? 0, above.depth);
|
|
62
|
+
entry.restrictedAncestors = above;
|
|
63
|
+
};
|
|
64
|
+
for (const grant of policy.grants) {
|
|
65
|
+
const row = policy.resources.get(grant.permission.resource);
|
|
66
|
+
for (const item of flattenGrantee(grant.to)) {
|
|
67
|
+
if (item.kind === "inherit") {
|
|
68
|
+
const inherited = inheritCondition(item, row, policy.resources);
|
|
69
|
+
addLinks(inherited?.hops ?? []);
|
|
70
|
+
addAbove(inherited?.restrictedAncestors);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (item.kind !== "relation") continue;
|
|
74
|
+
const condition = relationCondition(item, row, scopes, { resources: policy.resources });
|
|
75
|
+
if (condition?.op !== "related") continue;
|
|
76
|
+
const node = policy.resources.get(condition.resource);
|
|
77
|
+
if (node === void 0) continue;
|
|
78
|
+
addRelation(node, condition.relation);
|
|
79
|
+
const entry = entryFor(node);
|
|
80
|
+
if (condition.depth > 0 && isSelfParented(node)) entry.closure = Math.max(entry.closure ?? 0, condition.depth);
|
|
81
|
+
addLinks(condition.hops ?? []);
|
|
82
|
+
addAbove(condition.restrictedAncestors);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return plan;
|
|
86
|
+
}
|
|
87
|
+
/** The closure depth per walked resource, as `RlsSqlContext.graph` carries it. */
|
|
88
|
+
function closureDepths(plan) {
|
|
89
|
+
const out = {};
|
|
90
|
+
for (const [name, entry] of plan) if (entry.closure !== void 0) out[name] = entry.closure;
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The `permitted_<resource>_ids(relation)` arm for one concrete relation: ids
|
|
95
|
+
* of `resource` the subject holds it on, directly or through a group. `asked`
|
|
96
|
+
* are the relation names that include it, so a call for any of them (or for
|
|
97
|
+
* all, with null) reads this arm.
|
|
98
|
+
*/
|
|
99
|
+
function relationArm(ctx, plan, node, relation, asked, tables) {
|
|
100
|
+
const spec = node.relations[relation];
|
|
101
|
+
if (!isEdgeRelation(spec) && !isPrincipalRelation(spec) && (!isFieldRelation(spec) || spec.memberOf !== void 0)) throw configError(`PermDock CLI: relation '${relation}' on ${node.name} is not a graph relation RLS can compile`);
|
|
102
|
+
const guard = asked.length === 1 ? `(p_relation is null or p_relation = ${quoteLiteral(asked[0] ?? relation)})` : `(p_relation is null or p_relation in (${asked.map(quoteLiteral).join(", ")}))`;
|
|
103
|
+
return ` select a.id from (${graphSqlText(relationArmSql(node.name, relation, {
|
|
104
|
+
resources: new Map([...plan].map(([name, item]) => [name, item.node])),
|
|
105
|
+
...tables === void 0 ? {} : { tables },
|
|
106
|
+
qualify: qualifySqlTable,
|
|
107
|
+
idType: (resource) => idTypeOf(ctx, resource),
|
|
108
|
+
holders: (resource, groupRelation) => [{ text: `select ${qualified(ctx, graphHelper(resource))}(${quoteLiteral(groupRelation)})` }]
|
|
109
|
+
}), ctx)}) a\n where ${guard}${activeUserSql(ctx).map((part) => ` and ${part}`).join("")}`;
|
|
110
|
+
}
|
|
111
|
+
function permittedSql(ctx, plan, entry, tables) {
|
|
112
|
+
const fn = qualified(ctx, graphHelper(entry.node.name));
|
|
113
|
+
const asked = [...entry.relations].toSorted();
|
|
114
|
+
const arms = [...new Set(asked.flatMap((name) => expandRelation(entry.node, name)))].toSorted().map((relation) => relationArm(ctx, plan, entry.node, relation, asked.filter((name) => expandRelation(entry.node, name).includes(relation)), tables));
|
|
115
|
+
const idType = idTypeOf(ctx, entry.node.name);
|
|
116
|
+
if (arms.length === 0) arms.push(` select null::${idType} where false`);
|
|
117
|
+
const query = arms.join("\n union\n");
|
|
118
|
+
const comment = `-- ${entry.node.name}: ids the subject holds a relation on (all relations when p_relation is null)`;
|
|
119
|
+
const grants = `revoke execute on function ${fn}(text) from public, anon;
|
|
120
|
+
grant execute on function ${fn}(text) to authenticated;`;
|
|
121
|
+
if (memoizes(ctx)) return `${comment}
|
|
122
|
+
${memoizedSetofSql({
|
|
123
|
+
fn,
|
|
124
|
+
param: "p_relation text",
|
|
125
|
+
returns: `setof ${idType}`,
|
|
126
|
+
idType,
|
|
127
|
+
scope: `rel.${entry.node.name}`,
|
|
128
|
+
keySql: "coalesce(p_relation, '')",
|
|
129
|
+
userSql: memoUserSql(ctx, subjectIdSql(ctx)),
|
|
130
|
+
query,
|
|
131
|
+
...ctx.memo === void 0 ? {} : { api: ctx.memo },
|
|
132
|
+
grants
|
|
133
|
+
})}`;
|
|
134
|
+
return `${comment}
|
|
135
|
+
create or replace function ${fn}(p_relation text)
|
|
136
|
+
returns setof ${idType}
|
|
137
|
+
language sql
|
|
138
|
+
stable
|
|
139
|
+
security definer
|
|
140
|
+
cost 1000
|
|
141
|
+
set search_path = ''
|
|
142
|
+
as $$
|
|
143
|
+
${query}
|
|
144
|
+
$$;
|
|
145
|
+
${grants}`;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* `permdock_link_<resource>_<link>(ids)`: ids of `resource` whose link points
|
|
149
|
+
* into `ids`, read past the table's own policies.
|
|
150
|
+
*/
|
|
151
|
+
function linkSql(ctx, node, link, tables) {
|
|
152
|
+
const spec = Object.hasOwn(node.links, link) ? node.links[link] : void 0;
|
|
153
|
+
if (spec === void 0) throw configError(`PermDock CLI: ${node.name} has no link '${link}'`);
|
|
154
|
+
const fn = qualified(ctx, linkHelper(node.name, link));
|
|
155
|
+
const sourceType = idTypeOf(ctx, node.name);
|
|
156
|
+
const targetType = idTypeOf(ctx, spec.resource);
|
|
157
|
+
return `-- ${node.name}.${link}: rows whose ${spec.field} points at one of the given ${spec.resource} ids
|
|
158
|
+
create or replace function ${fn}(p_ids ${targetType}[])
|
|
159
|
+
returns setof ${sourceType}
|
|
160
|
+
language sql
|
|
161
|
+
stable
|
|
162
|
+
security definer
|
|
163
|
+
cost 1000
|
|
164
|
+
set search_path = ''
|
|
165
|
+
as $$
|
|
166
|
+
select t.${quoteIdent(node.id)} from ${quoteQualified(tableFor(node.name, tables))} t
|
|
167
|
+
where t.${quoteIdent(spec.field)} = any(p_ids)
|
|
168
|
+
$$;
|
|
169
|
+
revoke execute on function ${fn}(${targetType}[]) from public, anon;
|
|
170
|
+
grant execute on function ${fn}(${targetType}[]) to authenticated;`;
|
|
171
|
+
}
|
|
172
|
+
function closureTableSql(ctx) {
|
|
173
|
+
const table = qualified(ctx, CLOSURE.table);
|
|
174
|
+
return `-- the object graph: one row per (ancestor, descendant) within each walked resource's depth,
|
|
175
|
+
-- never crossing a restricted row; kept current by statement triggers on each self-parented table
|
|
176
|
+
create table if not exists ${table} (
|
|
177
|
+
resource text not null,
|
|
178
|
+
ancestor text not null,
|
|
179
|
+
descendant text not null,
|
|
180
|
+
depth integer not null check (depth >= 0),
|
|
181
|
+
primary key (resource, descendant, ancestor)
|
|
182
|
+
);
|
|
183
|
+
create index if not exists ${quoteIdent(`${CLOSURE.table}_ancestor`)} on ${table} (resource, ancestor);
|
|
184
|
+
alter table ${table} enable row level security;
|
|
185
|
+
revoke all on table ${table} from anon, authenticated, public;
|
|
186
|
+
grant select on table ${table} to authenticated;`;
|
|
187
|
+
}
|
|
188
|
+
function closureObjectsSql(ctx, entry, depth, tables) {
|
|
189
|
+
const { node } = entry;
|
|
190
|
+
const parent = node.parent;
|
|
191
|
+
if (parent === void 0) return "";
|
|
192
|
+
const name = node.name;
|
|
193
|
+
const sqlName = graphSqlName(name) ?? name;
|
|
194
|
+
const closure = qualified(ctx, CLOSURE.table);
|
|
195
|
+
const table = quoteQualified(tableFor(name, tables));
|
|
196
|
+
const id = quoteIdent(node.id);
|
|
197
|
+
const up = quoteIdent(parent.field);
|
|
198
|
+
const restricted = restrictedFor(node, "parent");
|
|
199
|
+
const stop = restricted === void 0 ? "false" : `coalesce(t.${quoteIdent(restricted)}, false)`;
|
|
200
|
+
const stopParent = restricted === void 0 ? "false" : `coalesce(p.${quoteIdent(restricted)}, false)`;
|
|
201
|
+
const refresh = qualified(ctx, `${CLOSURE.table}_${sqlName}`);
|
|
202
|
+
const changed = qualified(ctx, `${CLOSURE.table}_${sqlName}_changed`);
|
|
203
|
+
const literal = quoteLiteral(name);
|
|
204
|
+
const idType = idTypeOf(ctx, name);
|
|
205
|
+
const ancestor = idType === "text" ? "ancestor" : `ancestor::${idType}`;
|
|
206
|
+
const typed = (array) => idType === "text" ? array : `${array}::${idType}[]`;
|
|
207
|
+
const restrictedChanged = restricted === void 0 ? "" : ` or n.${quoteIdent(restricted)} is distinct from o.${quoteIdent(restricted)}`;
|
|
208
|
+
const trigger = (suffix) => quoteIdent(`${CLOSURE.table}_${sqlName}_${suffix}`);
|
|
209
|
+
return `-- ${name}: ${restricted === void 0 ? `rows reach their ancestors up to depth ${String(depth)}` : `rows reach their ancestors up to depth ${String(depth)}, stopping at a restricted row`}
|
|
210
|
+
drop policy if exists ${quoteIdent(`${CLOSURE.table}_${sqlName}`)} on ${closure};
|
|
211
|
+
create policy ${quoteIdent(`${CLOSURE.table}_${sqlName}`)} on ${closure}
|
|
212
|
+
for select to authenticated
|
|
213
|
+
using (resource = ${literal} and ${ancestor} in (select ${qualified(ctx, graphHelper(name))}(null)));
|
|
214
|
+
create or replace function ${refresh}(p_ids text[])
|
|
215
|
+
returns void
|
|
216
|
+
language plpgsql
|
|
217
|
+
security definer
|
|
218
|
+
set search_path = ''
|
|
219
|
+
as $$
|
|
220
|
+
declare
|
|
221
|
+
v_cycle text;
|
|
222
|
+
v_affected text[];
|
|
223
|
+
begin
|
|
224
|
+
with recursive walk(start, next, path) as (
|
|
225
|
+
select t.${id}, t.${up}, array[t.${id}::text]
|
|
226
|
+
from ${table} t
|
|
227
|
+
where t.${id} = any(${typed("p_ids")})
|
|
228
|
+
union all
|
|
229
|
+
select walk.start, t.${up}, walk.path || t.${id}::text
|
|
230
|
+
from walk join ${table} t on t.${id} = walk.next
|
|
231
|
+
where not (walk.next::text = any(walk.path))
|
|
232
|
+
)
|
|
233
|
+
select walk.start::text into v_cycle
|
|
234
|
+
from walk
|
|
235
|
+
where walk.next::text = any(walk.path)
|
|
236
|
+
limit 1;
|
|
237
|
+
if v_cycle is not null then
|
|
238
|
+
raise exception 'permdock: % % is its own ancestor', ${literal}, v_cycle
|
|
239
|
+
using errcode = 'check_violation';
|
|
240
|
+
end if;
|
|
241
|
+
with recursive down(id, level) as (
|
|
242
|
+
select t.${id}, 0
|
|
243
|
+
from ${table} t
|
|
244
|
+
where t.${id} = any(${typed("p_ids")}) or t.${up} = any(${typed("p_ids")})
|
|
245
|
+
union
|
|
246
|
+
select t.${id}, down.level + 1
|
|
247
|
+
from down join ${table} t on t.${up} = down.id
|
|
248
|
+
where down.level < ${String(depth)}
|
|
249
|
+
)
|
|
250
|
+
select coalesce(array_agg(distinct down.id::text), '{}') into v_affected from down;
|
|
251
|
+
delete from ${closure} c
|
|
252
|
+
where c.resource = ${literal}
|
|
253
|
+
and (c.descendant = any(p_ids) or c.descendant = any(v_affected));
|
|
254
|
+
insert into ${closure} (resource, ancestor, descendant, depth)
|
|
255
|
+
with recursive walk(descendant, ancestor, parent, depth, stop) as (
|
|
256
|
+
select t.${id}::text, t.${id}, t.${up}, 0, ${stop}
|
|
257
|
+
from ${table} t
|
|
258
|
+
where t.${id} = any(${typed("v_affected")})
|
|
259
|
+
union all
|
|
260
|
+
select walk.descendant, p.${id}, p.${up}, walk.depth + 1, ${stopParent}
|
|
261
|
+
from walk join ${table} p on p.${id} = walk.parent
|
|
262
|
+
where not walk.stop and walk.depth < ${String(depth)}
|
|
263
|
+
)
|
|
264
|
+
select ${literal}, walk.ancestor::text, walk.descendant, walk.depth from walk
|
|
265
|
+
on conflict do nothing;
|
|
266
|
+
end
|
|
267
|
+
$$;
|
|
268
|
+
revoke execute on function ${refresh}(text[]) from public, anon, authenticated;
|
|
269
|
+
create or replace function ${changed}()
|
|
270
|
+
returns trigger
|
|
271
|
+
language plpgsql
|
|
272
|
+
security definer
|
|
273
|
+
set search_path = ''
|
|
274
|
+
as $$
|
|
275
|
+
begin
|
|
276
|
+
if tg_op = 'TRUNCATE' then
|
|
277
|
+
delete from ${closure} where resource = ${literal};
|
|
278
|
+
elsif tg_op = 'INSERT' then
|
|
279
|
+
perform ${refresh}(array(select n.${id}::text from new_rows n));
|
|
280
|
+
elsif tg_op = 'DELETE' then
|
|
281
|
+
perform ${refresh}(array(select o.${id}::text from old_rows o));
|
|
282
|
+
else
|
|
283
|
+
perform ${refresh}(array(
|
|
284
|
+
select n.${id}::text
|
|
285
|
+
from new_rows n left join old_rows o on o.${id} = n.${id}
|
|
286
|
+
where o.${id} is null or n.${up} is distinct from o.${up}${restrictedChanged}
|
|
287
|
+
union
|
|
288
|
+
select o.${id}::text
|
|
289
|
+
from old_rows o left join new_rows n on n.${id} = o.${id}
|
|
290
|
+
where n.${id} is null
|
|
291
|
+
));
|
|
292
|
+
end if;
|
|
293
|
+
return null;
|
|
294
|
+
end
|
|
295
|
+
$$;
|
|
296
|
+
revoke execute on function ${changed}() from public, anon, authenticated;
|
|
297
|
+
drop trigger if exists ${trigger("insert")} on ${table};
|
|
298
|
+
create trigger ${trigger("insert")} after insert on ${table}
|
|
299
|
+
referencing new table as new_rows
|
|
300
|
+
for each statement execute function ${changed}();
|
|
301
|
+
drop trigger if exists ${trigger("update")} on ${table};
|
|
302
|
+
create trigger ${trigger("update")} after update on ${table}
|
|
303
|
+
referencing old table as old_rows new table as new_rows
|
|
304
|
+
for each statement execute function ${changed}();
|
|
305
|
+
drop trigger if exists ${trigger("delete")} on ${table};
|
|
306
|
+
create trigger ${trigger("delete")} after delete on ${table}
|
|
307
|
+
referencing old table as old_rows
|
|
308
|
+
for each statement execute function ${changed}();
|
|
309
|
+
drop trigger if exists ${trigger("truncate")} on ${table};
|
|
310
|
+
create trigger ${trigger("truncate")} after truncate on ${table}
|
|
311
|
+
for each statement execute function ${changed}();`;
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* One statement per walked table that fills the closure from the rows already
|
|
315
|
+
* stored. It is data, so it belongs in the seeds migration. `rls.seeds: 'view'`
|
|
316
|
+
* has no data migration, and the triggers fill the closure from later writes.
|
|
317
|
+
*/
|
|
318
|
+
function closureBackfillSql(ctx, plan, tables) {
|
|
319
|
+
if (ctx.seeds === "view") return "";
|
|
320
|
+
const lines = dependencyOrder(plan).flatMap((entry) => {
|
|
321
|
+
const { node } = entry;
|
|
322
|
+
if (entry.closure === void 0 || node.parent === void 0) return [];
|
|
323
|
+
const sqlName = graphSqlName(node.name) ?? node.name;
|
|
324
|
+
const refresh = qualified(ctx, `${CLOSURE.table}_${sqlName}`);
|
|
325
|
+
const table = quoteQualified(tableFor(node.name, tables));
|
|
326
|
+
return [`select ${refresh}(array(select t.${quoteIdent(node.id)}::text from ${table} t));`];
|
|
327
|
+
});
|
|
328
|
+
return lines.length === 0 ? "" : `-- closure backfill: one pass over each walked table after its triggers exist\n${lines.join("\n")}\n`;
|
|
329
|
+
}
|
|
330
|
+
function restrictedRowsHelperSql(ctx, plan, entry, tables) {
|
|
331
|
+
const above = entry.restrictedAncestors;
|
|
332
|
+
if (above === void 0) return "";
|
|
333
|
+
const fn = qualified(ctx, restrictedHelper(entry.node.name));
|
|
334
|
+
const body = graphSqlText(restrictedRowsSql(above, {
|
|
335
|
+
resources: new Map([...plan].map(([name, item]) => [name, item.node])),
|
|
336
|
+
...tables === void 0 ? {} : { tables },
|
|
337
|
+
qualify: qualifySqlTable,
|
|
338
|
+
idType: (resource) => idTypeOf(ctx, resource),
|
|
339
|
+
closure: `${helperSchema(ctx)}.${CLOSURE.table}`,
|
|
340
|
+
closureDepths: closureDepths(plan)
|
|
341
|
+
}), ctx);
|
|
342
|
+
return `-- ${entry.node.name}: rows a stopped link does not reach below: restricted, under a restricted row within ${String(above.depth - 1)} levels, or deeper
|
|
343
|
+
create or replace function ${fn}()
|
|
344
|
+
returns setof ${idTypeOf(ctx, entry.node.name)}
|
|
345
|
+
language sql
|
|
346
|
+
stable
|
|
347
|
+
security definer
|
|
348
|
+
cost 1000
|
|
349
|
+
set search_path = ''
|
|
350
|
+
as $$
|
|
351
|
+
${body}
|
|
352
|
+
$$;
|
|
353
|
+
revoke execute on function ${fn}() from public, anon;
|
|
354
|
+
grant execute on function ${fn}() to authenticated;`;
|
|
355
|
+
}
|
|
356
|
+
/** Group resources a resource's asked relations name, other than itself. */
|
|
357
|
+
function groupTargets(entry) {
|
|
358
|
+
const out = /* @__PURE__ */ new Set();
|
|
359
|
+
for (const asked of entry.relations) for (const name of expandRelation(entry.node, asked)) {
|
|
360
|
+
const spec = entry.node.relations[name];
|
|
361
|
+
const resources = isEdgeRelation(spec) ? groupEntries(spec).map((group) => group.resource) : [];
|
|
362
|
+
for (const resource of resources) if (resource !== entry.node.name) out.add(resource);
|
|
363
|
+
}
|
|
364
|
+
return [...out].toSorted();
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Plan entries by name, each after the group resources its helper calls (SQL
|
|
368
|
+
* function bodies are checked on create).
|
|
369
|
+
*/
|
|
370
|
+
function dependencyOrder(plan) {
|
|
371
|
+
const out = [];
|
|
372
|
+
const done = /* @__PURE__ */ new Set();
|
|
373
|
+
const visit = (name) => {
|
|
374
|
+
const entry = plan.get(name);
|
|
375
|
+
if (entry === void 0 || done.has(name)) return;
|
|
376
|
+
done.add(name);
|
|
377
|
+
for (const target of groupTargets(entry)) visit(target);
|
|
378
|
+
out.push(entry);
|
|
379
|
+
};
|
|
380
|
+
for (const name of [...plan.keys()].toSorted()) visit(name);
|
|
381
|
+
return out;
|
|
382
|
+
}
|
|
383
|
+
function graphIdsSql(ctx, plan, tables) {
|
|
384
|
+
return dependencyOrder(plan).filter((entry) => entry.relations.size > 0 || entry.closure !== void 0).map((entry) => permittedSql(ctx, plan, entry, tables)).join("\n");
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* The graph preamble: `permitted_<resource>_ids` for every resource a graph
|
|
388
|
+
* grant reads, and the closure table with its triggers for every self-parented
|
|
389
|
+
* resource a grant walks. Empty when no grant is a graph grant.
|
|
390
|
+
*/
|
|
391
|
+
function graphSql(ctx, plan, tables) {
|
|
392
|
+
if (plan.size === 0) return "";
|
|
393
|
+
const sqlNames = /* @__PURE__ */ new Map();
|
|
394
|
+
for (const name of plan.keys()) {
|
|
395
|
+
const helper = graphHelper(name);
|
|
396
|
+
const sql = graphSqlName(name) ?? name;
|
|
397
|
+
if (ctx.scopes.some((scope) => scope.name === sql)) throw configError(`PermDock CLI: resource '${name}' has graph relations and shares its SQL name with the ${sql} scope, so ${helper} would replace the scope helper; rename the resource (permdock doctor PD032)`);
|
|
398
|
+
const other = sqlNames.get(sql);
|
|
399
|
+
if (other !== void 0) throw configError(`PermDock CLI: resources '${other}' and '${name}' both name the SQL helper ${helper}; rename one (permdock doctor PD032)`);
|
|
400
|
+
sqlNames.set(sql, name);
|
|
401
|
+
}
|
|
402
|
+
const entries = dependencyOrder(plan);
|
|
403
|
+
const chunks = entries.flatMap((entry) => [...entry.relations.size === 0 && entry.closure === void 0 ? [] : [permittedSql(ctx, plan, entry, tables)], ...[...entry.links].toSorted().map((link) => linkSql(ctx, entry.node, link, tables))]);
|
|
404
|
+
const walked = entries.filter((entry) => entry.closure !== void 0);
|
|
405
|
+
if (walked.length > 0) {
|
|
406
|
+
chunks.push(closureTableSql(ctx));
|
|
407
|
+
for (const entry of walked) chunks.push(closureObjectsSql(ctx, entry, entry.closure ?? 0, tables));
|
|
408
|
+
for (const entry of walked) {
|
|
409
|
+
const helper = restrictedRowsHelperSql(ctx, plan, entry, tables);
|
|
410
|
+
if (helper !== "") chunks.push(helper);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
return `${chunks.join("\n\n")}\n`;
|
|
414
|
+
}
|
|
415
|
+
// src/cli/sql/policy-bundle.ts
|
|
416
|
+
/** The `format` member of a policy bundle. */
|
|
417
|
+
const POLICY_BUNDLE_FORMAT = "policy-bundle";
|
|
418
|
+
/** The table a bundle is loaded into, in the helpers schema. */
|
|
419
|
+
const POLICY_BUNDLE_TABLE = "permdock_policy_bundle";
|
|
420
|
+
/**
|
|
421
|
+
* The grant keys each role holds per scope, as the `permdock_role_keys` lookup
|
|
422
|
+
* reads them: sorted, without duplicates.
|
|
423
|
+
*/
|
|
424
|
+
function roleKeyMap(rows) {
|
|
425
|
+
const map = {};
|
|
426
|
+
for (const row of rows) {
|
|
427
|
+
const byRole = map[row.scope] ??= {};
|
|
428
|
+
const keys = byRole[row.role] ??= [];
|
|
429
|
+
if (!keys.includes(row.grantKey)) keys.push(row.grantKey);
|
|
430
|
+
}
|
|
431
|
+
return Object.fromEntries(Object.entries(map).toSorted(([a], [b]) => byCodeUnit(a, b)).map(([scope, byRole]) => [scope, Object.fromEntries(Object.entries(byRole).toSorted(([a], [b]) => byCodeUnit(a, b)).map(([role, keys]) => [role, keys.toSorted(byCodeUnit)]))]));
|
|
432
|
+
}
|
|
433
|
+
/** `sha-256:<base64url>` of a string's UTF-8 bytes. */
|
|
434
|
+
function bundleDigest(text) {
|
|
435
|
+
return `sha-256:${createHash("sha256").update(text, "utf8").digest("base64url")}`;
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* The bundle of a policy's static grants: `policy-bundle` v1, with the rows
|
|
439
|
+
* sorted and deduplicated and each key in the order RFC 8785 gives it, so the
|
|
440
|
+
* same policy always produces the same bytes and the same hash. `rows` are the
|
|
441
|
+
* `role_permissions` rows; `roleKeys` is the lookup the helpers read.
|
|
442
|
+
*/
|
|
443
|
+
function policyBundle(rows) {
|
|
444
|
+
const unique = /* @__PURE__ */ new Map();
|
|
445
|
+
for (const row of rows) unique.set(canonicalJson([
|
|
446
|
+
row.scope,
|
|
447
|
+
row.role,
|
|
448
|
+
row.grantKey,
|
|
449
|
+
row.permission
|
|
450
|
+
]), row);
|
|
451
|
+
const sorted = [...unique.entries()].toSorted(([a], [b]) => byCodeUnit(a, b)).map(([, row]) => row);
|
|
452
|
+
const text = canonicalJson({
|
|
453
|
+
format: POLICY_BUNDLE_FORMAT,
|
|
454
|
+
v: 1,
|
|
455
|
+
rows: sorted.map((row) => ({
|
|
456
|
+
effect: row.effect,
|
|
457
|
+
grant_key: row.grantKey,
|
|
458
|
+
permission: row.permission,
|
|
459
|
+
role: row.role,
|
|
460
|
+
scope: row.scope
|
|
461
|
+
})),
|
|
462
|
+
roleKeys: roleKeyMap(sorted)
|
|
463
|
+
});
|
|
464
|
+
return {
|
|
465
|
+
text,
|
|
466
|
+
hash: bundleDigest(text)
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
/** The SQL expression that recomputes `bundleDigest` over a `body` column. */
|
|
470
|
+
const DIGEST_SQL = "'sha-256:' || translate(rtrim(encode(sha256(convert_to(body, 'UTF8')), 'base64'), '='), '+/', '-_')";
|
|
471
|
+
/**
|
|
472
|
+
* The table a bundle is loaded into. The check recomputes the digest, so a body
|
|
473
|
+
* stored under a hash it does not have is refused; `doc` is the parsed body the
|
|
474
|
+
* helpers read.
|
|
475
|
+
*/
|
|
476
|
+
function bundleTableSql(ctx) {
|
|
477
|
+
const table = qualified(ctx, POLICY_BUNDLE_TABLE);
|
|
478
|
+
return `create table if not exists ${table} (
|
|
479
|
+
hash text primary key,
|
|
480
|
+
body text not null,
|
|
481
|
+
doc jsonb generated always as (body::jsonb) stored,
|
|
482
|
+
constraint permdock_policy_bundle_digest check (hash = ${DIGEST_SQL})
|
|
483
|
+
);
|
|
484
|
+
alter table ${table} enable row level security;
|
|
485
|
+
revoke all on table ${table} from anon, authenticated, public;`;
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Loads a bundle: an insert keyed by its hash. A bundle that is already there
|
|
489
|
+
* stays as it is, so the statement is safe to run twice.
|
|
490
|
+
*/
|
|
491
|
+
function bundleLoaderSql(ctx, bundle) {
|
|
492
|
+
return `insert into ${qualified(ctx, POLICY_BUNDLE_TABLE)} (hash, body) values
|
|
493
|
+
(${quoteLiteral(bundle.hash)}, ${quoteLiteral(bundle.text)})
|
|
494
|
+
on conflict (hash) do nothing;`;
|
|
495
|
+
}
|
|
496
|
+
// src/cli/sql/digest.ts
|
|
497
|
+
/**
|
|
498
|
+
* Adds the `sha-256:` digest of everything after the first line to that line,
|
|
499
|
+
* so a reader can tell a generated helpers file from an edited or older one.
|
|
500
|
+
* The digest covers the text a database executes, not the version of the CLI,
|
|
501
|
+
* so a release that writes the same helpers writes the same bytes.
|
|
502
|
+
*/
|
|
503
|
+
function stampHelpers(text) {
|
|
504
|
+
const newline = text.indexOf("\n");
|
|
505
|
+
if (newline < 0) return text;
|
|
506
|
+
const first = text.slice(0, newline);
|
|
507
|
+
const rest = text.slice(newline + 1);
|
|
508
|
+
return `${first} ${bundleDigest(rest)}\n${rest}`;
|
|
509
|
+
}
|
|
510
|
+
// src/cli/supabase-hook/teams.ts
|
|
511
|
+
/** The reader `supabase.hook.teams` writes when no team scope does. */
|
|
512
|
+
const HOOK_TEAM_READER = "member_team_ids_for";
|
|
513
|
+
/**
|
|
514
|
+
* The `member_team_ids_of` helper the hook file writes from
|
|
515
|
+
* `supabase.hook.teams`, or `undefined` when there is no teams table or `rls
|
|
516
|
+
* generate` already writes one for a `team` or `teams` scope.
|
|
517
|
+
*/
|
|
518
|
+
function hookTeamsHelper(parts) {
|
|
519
|
+
if (parts.hook.teams === void 0) return;
|
|
520
|
+
return parts.helpers.memberFor.some((scope) => isTeamScope(scope)) ? void 0 : memberOfHelper("team");
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* The `(p_user uuid, p_active text default null)` reader the hook's `team_ids`
|
|
524
|
+
* claim and `subject_for` call, unqualified: `member_<scope>_ids_for` of a
|
|
525
|
+
* `team` or `teams` scope, else the one `supabase.hook.teams` writes.
|
|
526
|
+
*/
|
|
527
|
+
function hookTeamReader(parts) {
|
|
528
|
+
const scope = parts.helpers.memberFor.find((name) => isTeamScope(name));
|
|
529
|
+
return scope === void 0 ? HOOK_TEAM_READER : memberForHelper(scope);
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* `member_team_ids_for` and `member_team_ids_of` for the helpers file.
|
|
533
|
+
* `member_team_ids_for` takes the user and never compares it with `auth.uid()`;
|
|
534
|
+
* it skips disabled rows, a suspended user and a suspended tenant. The wrapper
|
|
535
|
+
* answers the caller only. Empty when a team scope already writes the same
|
|
536
|
+
* names.
|
|
537
|
+
*/
|
|
538
|
+
function hookTeamReadersSql(ctx) {
|
|
539
|
+
const teams = ctx.hookTeams;
|
|
540
|
+
if (teams === void 0 || ctx.scopes.some((scope) => hasMemberOf(ctx, scope.name))) return "";
|
|
541
|
+
const definer = ctx.hookSecurity === "definer";
|
|
542
|
+
const schema = quoteIdent(helperSchema(ctx));
|
|
543
|
+
const reader = `${schema}.${quoteIdent(HOOK_TEAM_READER)}`;
|
|
544
|
+
const wrapper = `${schema}.${quoteIdent(memberOfHelper("team"))}`;
|
|
545
|
+
const root = ctx.scopes[0]?.name;
|
|
546
|
+
const tenantRow = root === void 0 ? void 0 : ctx.suspension?.scopes?.[root];
|
|
547
|
+
const filters = [
|
|
548
|
+
...teams.disabledAt === void 0 ? [] : [` and t.${quoteIdent(teams.disabledAt)} is null`],
|
|
549
|
+
...activeUserSql(ctx, "p_user").map((part) => ` and ${part}`),
|
|
550
|
+
...tenantRow === void 0 || teams.tenant === void 0 ? [] : [` and ${activeRowSql(tenantRow, `t.${quoteIdent(teams.tenant)}`)}`]
|
|
551
|
+
];
|
|
552
|
+
const order = teams.tenant === void 0 ? `t.${quoteIdent(teams.team)}` : `(p_active is not null and t.${quoteIdent(teams.tenant)}::text is not distinct from p_active) desc, t.${quoteIdent(teams.team)}`;
|
|
553
|
+
return `-- teams of p_user from supabase.hook.teams; ${definer ? "only the hook's owner executes it" : "execute is supabase_auth_admin only"}
|
|
554
|
+
create or replace function ${reader}(p_user uuid, p_active text default null)
|
|
555
|
+
returns setof uuid
|
|
556
|
+
language sql
|
|
557
|
+
stable
|
|
558
|
+
security definer
|
|
559
|
+
set search_path = ''
|
|
560
|
+
as $$
|
|
561
|
+
select t.${quoteIdent(teams.team)}
|
|
562
|
+
from ${quoteQualified(teams.table)} t
|
|
563
|
+
where t.${quoteIdent(teams.user)} = p_user
|
|
564
|
+
${filters.join("\n")}
|
|
565
|
+
order by ${order}
|
|
566
|
+
$$;
|
|
567
|
+
revoke execute on function ${reader}(uuid, text) from public, anon, authenticated;${definer ? "" : `\ngrant execute on function ${reader}(uuid, text) to supabase_auth_admin;`}
|
|
568
|
+
|
|
569
|
+
-- the caller's teams only, for better-supabase's teamIdsOf
|
|
570
|
+
create or replace function ${wrapper}(p_user uuid)
|
|
571
|
+
returns setof uuid
|
|
572
|
+
language sql
|
|
573
|
+
stable
|
|
574
|
+
security definer
|
|
575
|
+
set search_path = ''
|
|
576
|
+
as $$
|
|
577
|
+
select m.id
|
|
578
|
+
from ${reader}(p_user, null) as m(id)
|
|
579
|
+
where p_user = (select ${schema}.permdock_user_id())
|
|
580
|
+
$$;
|
|
581
|
+
revoke execute on function ${wrapper}(uuid) from public, anon;
|
|
582
|
+
grant execute on function ${wrapper}(uuid) to authenticated;`;
|
|
583
|
+
}
|
|
584
|
+
// src/cli/rls/api-keys.ts
|
|
585
|
+
const API_KEY_ALLOWS = "permdock_api_key_allows";
|
|
586
|
+
const DEFAULTS = {
|
|
587
|
+
claim: "api_key",
|
|
588
|
+
scopes: "scopes",
|
|
589
|
+
tenant: "tenant",
|
|
590
|
+
roles: "roles"
|
|
591
|
+
};
|
|
592
|
+
function field(settings, name) {
|
|
593
|
+
const value = settings[name] ?? DEFAULTS[name];
|
|
594
|
+
if (typeof value !== "string" || !SQL_IDENT.test(value)) throw configError(`PermDock CLI: rls.apiKeys.${name} must be a claim field name matching ${SQL_IDENT.source}`);
|
|
595
|
+
return value;
|
|
596
|
+
}
|
|
597
|
+
function apiKeyFields(setting) {
|
|
598
|
+
const settings = setting === true ? {} : setting;
|
|
599
|
+
return {
|
|
600
|
+
claim: field(settings, "claim"),
|
|
601
|
+
scopes: field(settings, "scopes"),
|
|
602
|
+
tenant: field(settings, "tenant"),
|
|
603
|
+
roles: field(settings, "roles"),
|
|
604
|
+
serviceRoles: [...new Set(settings.serviceRoles ?? [])]
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
function apiKeysPlan(setting, declared, renamed) {
|
|
608
|
+
if (setting === void 0) return;
|
|
609
|
+
const fields = apiKeyFields(setting);
|
|
610
|
+
const unknown = fields.serviceRoles.filter((role) => !declared.has(role));
|
|
611
|
+
if (unknown.length > 0) throw configError(`PermDock CLI: rls.apiKeys.serviceRoles names roles the policy does not declare: ${unknown.join(", ")}`);
|
|
612
|
+
return {
|
|
613
|
+
...fields,
|
|
614
|
+
...Object.keys(renamed).length === 0 ? {} : { renamed }
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
function keyOf(ctx, plan) {
|
|
618
|
+
return `(select ${subjectClaimJsonSql(ctx, plan.claim)} as k) api_key`;
|
|
619
|
+
}
|
|
620
|
+
function permissionOf(plan, expr) {
|
|
621
|
+
return plan.renamed === void 0 ? expr : `coalesce(${quoteLiteral(JSON.stringify(plan.renamed))}::jsonb ->> ${expr}, ${expr})`;
|
|
622
|
+
}
|
|
623
|
+
function apiKeyAllowsCall(ctx, grant) {
|
|
624
|
+
return `${qualified(ctx, API_KEY_ALLOWS)}(${grant})`;
|
|
625
|
+
}
|
|
626
|
+
function apiKeyAllowsSql(ctx, plan, anonExecute) {
|
|
627
|
+
const fn = qualified(ctx, API_KEY_ALLOWS);
|
|
628
|
+
const scopes = `k -> ${quoteLiteral(plan.scopes)}`;
|
|
629
|
+
const grants = anonExecute ? `revoke execute on function ${fn}(text) from public;
|
|
630
|
+
grant execute on function ${fn}(text) to anon, authenticated;` : `revoke execute on function ${fn}(text) from public, anon;
|
|
631
|
+
grant execute on function ${fn}(text) to authenticated;`;
|
|
632
|
+
return `-- API keys: the ${plan.claim} claim's ${plan.scopes} list is a ceiling on every allow; denies always apply, and a request without the claim is not limited
|
|
633
|
+
create or replace function ${fn}(p_grant text)
|
|
634
|
+
returns boolean
|
|
635
|
+
language sql
|
|
636
|
+
stable
|
|
637
|
+
security definer
|
|
638
|
+
set search_path = ''
|
|
639
|
+
as $$
|
|
640
|
+
select case
|
|
641
|
+
when k is null or k = 'null'::jsonb then true
|
|
642
|
+
when exists (
|
|
643
|
+
select 1 from ${qualified(ctx, "role_permissions")} rp
|
|
644
|
+
where rp.grant_key = p_grant and rp.effect = 'deny'
|
|
645
|
+
) then true
|
|
646
|
+
when jsonb_typeof(k) is distinct from 'object' or jsonb_typeof(${scopes}) is distinct from 'array' then false
|
|
647
|
+
else exists (
|
|
648
|
+
select 1
|
|
649
|
+
from jsonb_array_elements_text(${scopes}) s(permission)
|
|
650
|
+
where ${permissionOf(plan, "s.permission")} = split_part(split_part(p_grant, '#', 1), '@', 1)
|
|
651
|
+
)
|
|
652
|
+
end
|
|
653
|
+
from ${keyOf(ctx, plan)}
|
|
654
|
+
$$;
|
|
655
|
+
${grants}`;
|
|
656
|
+
}
|
|
657
|
+
function serviceRolesJson(plan) {
|
|
658
|
+
return `${quoteLiteral(JSON.stringify(plan.serviceRoles))}::jsonb`;
|
|
659
|
+
}
|
|
660
|
+
function serviceKeyRows(ctx, plan) {
|
|
661
|
+
const roles = `k -> ${quoteLiteral(plan.roles)}`;
|
|
662
|
+
return ` from ${keyOf(ctx, plan)}
|
|
663
|
+
cross join lateral jsonb_array_elements_text(
|
|
664
|
+
case jsonb_typeof(${roles}) when 'array' then ${roles} else ${serviceRolesJson(plan)} end
|
|
665
|
+
) r(role)`;
|
|
666
|
+
}
|
|
667
|
+
function serviceKeyFilters(ctx, plan, root, permission) {
|
|
668
|
+
const tenant = `k ->> ${quoteLiteral(plan.tenant)}`;
|
|
669
|
+
return [
|
|
670
|
+
`jsonb_typeof(k) = 'object'`,
|
|
671
|
+
`coalesce(${subjectIdSql(ctx)}::text, '') = ''`,
|
|
672
|
+
`coalesce(${tenant}, '') <> ''`,
|
|
673
|
+
...activeInstancesSql(ctx, root, (name) => name === root ? tenant : void 0, permission)
|
|
674
|
+
];
|
|
675
|
+
}
|
|
676
|
+
function serviceKeyIdsSql(ctx, plan, root, type) {
|
|
677
|
+
const kind = kindFilterSql(ctx, "r.role", { value: "credential" });
|
|
678
|
+
const set = ctx.grantSet === true;
|
|
679
|
+
const filters = [
|
|
680
|
+
...serviceKeyFilters(ctx, plan, root, grantPermissionSql(set ? "rp.grant_key" : "p_grant")),
|
|
681
|
+
...set ? [] : ["rp.grant_key = p_grant"],
|
|
682
|
+
`rp.scope = ${quoteLiteral(root)}`,
|
|
683
|
+
...kind === void 0 ? [] : [kind]
|
|
684
|
+
];
|
|
685
|
+
return ` select (k ->> ${quoteLiteral(plan.tenant)})::${type}${set ? ", rp.grant_key" : ""}
|
|
686
|
+
${serviceKeyRows(ctx, plan)}
|
|
687
|
+
join ${qualified(ctx, "role_permissions")} rp on rp.role = r.role
|
|
688
|
+
where ${filters.join("\n and ")}`;
|
|
689
|
+
}
|
|
690
|
+
function serviceKeyMemberSql(ctx, plan, root, type) {
|
|
691
|
+
return ` select distinct (k ->> ${quoteLiteral(plan.tenant)})::${type}
|
|
692
|
+
${serviceKeyRows(ctx, plan)}
|
|
693
|
+
where ${serviceKeyFilters(ctx, plan, root).join("\n and ")}`;
|
|
694
|
+
}
|
|
695
|
+
function ceilingIdsSql(body, allows) {
|
|
696
|
+
return ` select ids.id
|
|
697
|
+
from (
|
|
698
|
+
${body}
|
|
699
|
+
) ids(id)
|
|
700
|
+
where ${allows}`;
|
|
701
|
+
}
|
|
702
|
+
function ceilingHasSql(body, allows) {
|
|
703
|
+
return ` select ${allows} and coalesce((
|
|
704
|
+
${body}
|
|
705
|
+
), false)`;
|
|
706
|
+
}
|
|
707
|
+
// src/cli/rls/capabilities.ts
|
|
708
|
+
/**
|
|
709
|
+
* The helper `--capabilities` adds: ids of one resource a link capability claim
|
|
710
|
+
* reaches. Part of the SQL contract.
|
|
711
|
+
*/
|
|
712
|
+
const CAPABILITIES = { ids: "permdock_capability_ids" };
|
|
713
|
+
/**
|
|
714
|
+
* The `anon` branch access for a resource-scoped grant reached through a link
|
|
715
|
+
* capability: the row's `field` holds an id the capability claim names for
|
|
716
|
+
* `resource`, `role` and `permission`. Uncorrelated, so it runs once per
|
|
717
|
+
* statement; the column is compared as text because the claim holds text.
|
|
718
|
+
*/
|
|
719
|
+
function capabilityAccessSql(ctx, field, resource, role, permission) {
|
|
720
|
+
const args = [
|
|
721
|
+
resource,
|
|
722
|
+
role,
|
|
723
|
+
permission
|
|
724
|
+
].map(quoteLiteral).join(", ");
|
|
725
|
+
return `${quoteIdent(field)}::text in (select ${qualified(ctx, CAPABILITIES.ids)}(${args}))`;
|
|
726
|
+
}
|
|
727
|
+
function capabilitiesSql(ctx) {
|
|
728
|
+
if (ctx.capabilities !== true) return "";
|
|
729
|
+
const fn = qualified(ctx, CAPABILITIES.ids);
|
|
730
|
+
return `-- link capabilities: the capability claim exchangeCapability mints (role anon, short-lived)
|
|
731
|
+
create or replace function ${fn}(p_resource text, p_role text, p_permission text)
|
|
732
|
+
returns setof text
|
|
733
|
+
language sql
|
|
734
|
+
stable
|
|
735
|
+
set search_path = ''
|
|
736
|
+
as $$
|
|
737
|
+
select c -> 'on' ->> 'id'
|
|
738
|
+
from (select ${subjectClaimJsonSql(ctx, "capability")} as c) capability
|
|
739
|
+
where jsonb_typeof(c) = 'object'
|
|
740
|
+
and c ->> 'v' = '1'
|
|
741
|
+
and c ->> 'holder' = 'link'
|
|
742
|
+
and c -> 'on' ->> 'resource' = p_resource
|
|
743
|
+
and jsonb_typeof(c -> 'roles') = 'array'
|
|
744
|
+
and c -> 'roles' @> jsonb_build_array(p_role)
|
|
745
|
+
and (c -> 'permissions' is null or c -> 'permissions' @> jsonb_build_array(p_permission))
|
|
746
|
+
and jsonb_typeof(c -> 'expires_at') = 'number'
|
|
747
|
+
and (c ->> 'expires_at')::numeric > extract(epoch from now())
|
|
748
|
+
$$;
|
|
749
|
+
revoke execute on function ${fn}(text, text, text) from public;
|
|
750
|
+
grant execute on function ${fn}(text, text, text) to anon, authenticated;`;
|
|
751
|
+
}
|
|
752
|
+
// src/cli/rls/custom-role-by-id.ts
|
|
753
|
+
const PREFIX = "PermDock CLI";
|
|
754
|
+
const col = (name) => `r.${quoteIdent(name)}`;
|
|
755
|
+
/**
|
|
756
|
+
* Custom-role functions keyed by the application's role row
|
|
757
|
+
* (`rls.customRoleWrites.roles.primaryKey`): the tenant, scope, instance and
|
|
758
|
+
* name come from the row, never from the caller. The writers delegate to
|
|
759
|
+
* `permdock_replace_custom_role_grants` (or its trusted variant), so every
|
|
760
|
+
* caller and definition check applies, and keep the stored denies and includes.
|
|
761
|
+
* The reader returns declared allow keys only and is executable by
|
|
762
|
+
* `rls.trustedReaders` alone.
|
|
763
|
+
*/
|
|
764
|
+
function customRoleByIdSql(ctx, trustedReaders) {
|
|
765
|
+
const custom = ctx.customRoles;
|
|
766
|
+
const roles = custom?.table;
|
|
767
|
+
const root = ctx.scopes[0]?.name;
|
|
768
|
+
if (custom === void 0 || roles?.primaryKey === void 0 || ctx.authorize !== "database" || root === void 0) return "";
|
|
769
|
+
const pk = roles.primaryKey;
|
|
770
|
+
if (pk === "") throw configError(`${PREFIX}: rls.customRoleWrites.roles.primaryKey names no column`);
|
|
771
|
+
const leveled = custom.levels === true;
|
|
772
|
+
const tenantType = tenantTypeOf(ctx);
|
|
773
|
+
const table = quoteQualified(roles.table);
|
|
774
|
+
const idType = `${table}.${quoteIdent(pk)}%type`;
|
|
775
|
+
const perms = qualified(ctx, CUSTOM_ROLES.permissions);
|
|
776
|
+
const includes = qualified(ctx, CUSTOM_ROLES.includes);
|
|
777
|
+
const replace = qualified(ctx, CUSTOM_ROLES.replace);
|
|
778
|
+
const trustedReplace = qualified(ctx, CUSTOM_ROLES.trustedReplace);
|
|
779
|
+
const byId = qualified(ctx, CUSTOM_ROLES.replaceById);
|
|
780
|
+
const trustedById = qualified(ctx, CUSTOM_ROLES.trustedReplaceById);
|
|
781
|
+
const reader = qualified(ctx, CUSTOM_ROLES.trustedReadById);
|
|
782
|
+
const renames = Object.entries(custom.renamed ?? {}).toSorted(byKey);
|
|
783
|
+
const current = (expr) => currentKeyExpr(renames, expr);
|
|
784
|
+
const declaredKeys = sqlTextArray(custom.permissions ?? []);
|
|
785
|
+
const declaredRoles = sqlTextArray(custom.declared);
|
|
786
|
+
const tenant = roles.tenant === void 0 ? `null::${tenantType}` : `${col(roles.tenant)}::${tenantType}`;
|
|
787
|
+
const scope = rolesTableScope(roles, tenant, root, col);
|
|
788
|
+
const scopeId = roles.id === void 0 || roles.tenant === void 0 ? "null::text" : `case when ${tenant} is null then null else ${col(roles.id)}::text end`;
|
|
789
|
+
const skipped = roles.skip === void 0 || roles.tenant === void 0 ? "false" : `(${tenant} is not null and coalesce(${col(roles.skip)}, false))`;
|
|
790
|
+
const match = "(v_tenant is null and c.tenant_id is null or c.tenant_id = v_tenant) and c.scope = v_scope and (v_scope_id is null and c.scope_id is null or c.scope_id = v_scope_id) and c.role = v_key";
|
|
791
|
+
const audit = custom.audit;
|
|
792
|
+
const auditCall = audit === void 0 ? "" : `
|
|
793
|
+
perform ${quoteQualified(audit.function)}(${[
|
|
794
|
+
"event_type => 'permdock.custom_role.replaced'",
|
|
795
|
+
"target_type => 'role'",
|
|
796
|
+
"record_id => p_role_id::text",
|
|
797
|
+
"tenant => v_tenant",
|
|
798
|
+
"metadata => jsonb_build_object('operation', 'replace', 'role', v_key, 'permissions', p_permissions)",
|
|
799
|
+
...Object.entries(audit.args ?? {}).toSorted(byKey).map(([name, value]) => `${quoteIdent(name)} => ${quoteLiteral(value)}`)
|
|
800
|
+
].join(", ")});`;
|
|
801
|
+
const body = (write) => `declare
|
|
802
|
+
v_tenant ${tenantType};
|
|
803
|
+
v_scope text;
|
|
804
|
+
v_scope_id text;
|
|
805
|
+
v_key text;
|
|
806
|
+
v_skipped boolean;
|
|
807
|
+
v_deny text[];
|
|
808
|
+
v_include text[];
|
|
809
|
+
begin
|
|
810
|
+
select ${tenant}, ${scope}, ${scopeId}, ${col(roles.key)}::text, ${skipped}
|
|
811
|
+
into v_tenant, v_scope, v_scope_id, v_key, v_skipped
|
|
812
|
+
from ${table} r
|
|
813
|
+
where ${col(pk)} = p_role_id;
|
|
814
|
+
if not found then
|
|
815
|
+
${raiseSql(" ", "P0002", "'permdock: no role row has id ' || coalesce(p_role_id::text, 'null')", "unknown-role")}
|
|
816
|
+
end if;
|
|
817
|
+
if v_skipped or v_key = any(${declaredRoles}) then
|
|
818
|
+
${raiseSql(" ", "22023", "'permdock: ' || coalesce(v_key, 'null') || ' is a declared role, not a custom role'", "declared-role")}
|
|
819
|
+
end if;
|
|
820
|
+
select array_agg(c.permission) into v_deny
|
|
821
|
+
from ${perms} c
|
|
822
|
+
where ${match} and c.effect = 'deny';
|
|
823
|
+
select array_agg(c.include_role) into v_include
|
|
824
|
+
from ${includes} c
|
|
825
|
+
where ${match};
|
|
826
|
+
perform ${write}(v_tenant, v_scope, v_scope_id, v_key, p_permissions, v_deny, v_include);${auditCall}
|
|
827
|
+
end;`;
|
|
828
|
+
const writer = (comment, name, write, member) => `-- ${comment}
|
|
829
|
+
create or replace function ${name}(p_role_id ${idType}, p_permissions text[])
|
|
830
|
+
returns void
|
|
831
|
+
language plpgsql
|
|
832
|
+
volatile
|
|
833
|
+
security definer
|
|
834
|
+
set search_path = ''
|
|
835
|
+
as $$
|
|
836
|
+
${body(write)}
|
|
837
|
+
$$;
|
|
838
|
+
${member ? `revoke execute on function ${name}(${idType}, text[]) from public, anon;
|
|
839
|
+
grant execute on function ${name}(${idType}, text[]) to authenticated;` : `revoke execute on function ${name}(${idType}, text[]) from public, anon, authenticated;`}`;
|
|
840
|
+
const readerEntry = leveled ? `${current("c.permission")} || coalesce('@' || c.level, '')` : current("c.permission");
|
|
841
|
+
const readerGrant = trustedReaders === void 0 || trustedReaders.length === 0 ? "" : `\n${trustedReaderGrants(ctx, `${reader}(text[], ${tenantType})`, trustedReaders)}`;
|
|
842
|
+
return `${writer("save a custom role by its row id: the row supplies tenant, scope, instance and name; the caller checks of permdock_replace_custom_role_grants apply, and stored denies and includes stay", byId, replace, true)}
|
|
843
|
+
|
|
844
|
+
${writer("save a custom role by its row id for a trusted caller: the definition checks without the caller checks", trustedById, trustedReplace, false)}
|
|
845
|
+
|
|
846
|
+
-- the declared allow keys of custom roles by their row ids as text, for a trusted reader; with p_tenant, an id of another tenant is refused
|
|
847
|
+
create or replace function ${reader}(p_role_ids text[], p_tenant ${tenantType} default null)
|
|
848
|
+
returns table (role_id text, permission text)
|
|
849
|
+
language plpgsql
|
|
850
|
+
stable
|
|
851
|
+
security definer
|
|
852
|
+
set search_path = ''
|
|
853
|
+
as $$
|
|
854
|
+
begin
|
|
855
|
+
if p_tenant is not null and exists (
|
|
856
|
+
select 1 from ${table} r
|
|
857
|
+
where ${col(pk)}::text = any(p_role_ids) and ${tenant} is distinct from p_tenant
|
|
858
|
+
) then
|
|
859
|
+
${raiseSql(" ", "42501", "'permdock: a role id belongs to another tenant than ' || p_tenant::text", "not-member")}
|
|
860
|
+
end if;
|
|
861
|
+
return query
|
|
862
|
+
select distinct v.role_id, ${readerEntry}
|
|
863
|
+
from (
|
|
864
|
+
select ${col(pk)}::text as role_id, ${tenant} as tenant_id, ${scope} as scope, ${scopeId} as scope_id, ${col(roles.key)}::text as role
|
|
865
|
+
from ${table} r
|
|
866
|
+
where ${col(pk)}::text = any(p_role_ids)
|
|
867
|
+
and not ${skipped}
|
|
868
|
+
and not (${col(roles.key)}::text = any(${declaredRoles}))
|
|
869
|
+
) v
|
|
870
|
+
join ${perms} c
|
|
871
|
+
on (v.tenant_id is null and c.tenant_id is null or c.tenant_id = v.tenant_id)
|
|
872
|
+
and c.scope = v.scope
|
|
873
|
+
and (v.scope_id is null and c.scope_id is null or c.scope_id = v.scope_id)
|
|
874
|
+
and c.role = v.role
|
|
875
|
+
where c.effect = 'allow'
|
|
876
|
+
and ${current("c.permission")} = any(${declaredKeys})
|
|
877
|
+
order by 1, 2;
|
|
878
|
+
end;
|
|
879
|
+
$$;
|
|
880
|
+
revoke execute on function ${reader}(text[], ${tenantType}) from public, anon, authenticated;${readerGrant}`;
|
|
881
|
+
}
|
|
882
|
+
// src/cli/rls/custom-role-cascade.ts
|
|
883
|
+
/** `row.column`, for a trigger's `old` or `new`. */
|
|
884
|
+
function rowColumn(row, name) {
|
|
885
|
+
return `${row}.${quoteIdent(name)}`;
|
|
886
|
+
}
|
|
887
|
+
/** The custom-role rows of the role a trigger's `v_<prefix>_*` variables name. */
|
|
888
|
+
function cascadeMatch(prefix) {
|
|
889
|
+
return `(v_${prefix}_tenant is null and c.tenant_id is null or c.tenant_id = v_${prefix}_tenant) and c.scope = v_${prefix}_scope and (v_${prefix}_id is null and c.scope_id is null or c.scope_id = v_${prefix}_id) and c.role = v_${prefix}_key`;
|
|
890
|
+
}
|
|
891
|
+
/**
|
|
892
|
+
* The trigger on the application's roles table (`rls.customRoleWrites.roles`):
|
|
893
|
+
* a rename, a move to another tenant, scope or instance, or a delete of a
|
|
894
|
+
* custom role's row carries its grants and includes along. A signed-in caller
|
|
895
|
+
* passes the write functions' checks unless the transaction set
|
|
896
|
+
* `permdock.sync`: authority over the stored definition where it was, and,
|
|
897
|
+
* after a move, membership and authority where it lands and entries inside that
|
|
898
|
+
* scope's ceiling. Other paths (a migration, a job, a nested trigger) move the
|
|
899
|
+
* rows as the function owner.
|
|
900
|
+
*/
|
|
901
|
+
function customRoleCascadeSql(ctx) {
|
|
902
|
+
const custom = ctx.customRoles;
|
|
903
|
+
const table = custom?.table;
|
|
904
|
+
const root = ctx.scopes[0]?.name;
|
|
905
|
+
if (custom === void 0 || table === void 0 || root === void 0) return "";
|
|
906
|
+
const tenantType = tenantTypeOf(ctx);
|
|
907
|
+
const perms = qualified(ctx, CUSTOM_ROLES.permissions);
|
|
908
|
+
const includes = qualified(ctx, CUSTOM_ROLES.includes);
|
|
909
|
+
const fn = qualified(ctx, CUSTOM_ROLES.cascade);
|
|
910
|
+
const target = quoteTable(qualifySqlTable(table.table));
|
|
911
|
+
const tenant = (row) => table.tenant === void 0 ? `null::${tenantType}` : `${rowColumn(row, table.tenant)}::${tenantType}`;
|
|
912
|
+
const scope = (row) => rolesTableScope(table, tenant(row), root, (name) => rowColumn(row, name));
|
|
913
|
+
const id = (row) => table.id === void 0 || table.tenant === void 0 ? "null::text" : `case when ${tenant(row)} is null then null else ${rowColumn(row, table.id)}::text end`;
|
|
914
|
+
const skipped = (row) => table.skip === void 0 || table.tenant === void 0 ? "false" : `(${tenant(row)} is not null and coalesce(${rowColumn(row, table.skip)}, false))`;
|
|
915
|
+
const guard = qualified(ctx, CUSTOM_ROLES.guard);
|
|
916
|
+
const entries = qualified(ctx, CUSTOM_ROLES.entries);
|
|
917
|
+
const allowEntryOf = `c.${allowEntry(ctx)}`;
|
|
918
|
+
return `-- the application's roles table: renames, moves and deletes of a custom role carry its grants and includes
|
|
919
|
+
create or replace function ${fn}()
|
|
920
|
+
returns trigger
|
|
921
|
+
language plpgsql
|
|
922
|
+
volatile
|
|
923
|
+
security definer
|
|
924
|
+
set search_path = ''
|
|
925
|
+
as $$
|
|
926
|
+
declare
|
|
927
|
+
v_old_tenant ${tenantType} := ${tenant("old")};
|
|
928
|
+
v_old_scope text := ${scope("old")};
|
|
929
|
+
v_old_id text := ${id("old")};
|
|
930
|
+
v_old_key text := ${rowColumn("old", table.key)}::text;
|
|
931
|
+
v_new_tenant ${tenantType};
|
|
932
|
+
v_new_scope text;
|
|
933
|
+
v_new_id text;
|
|
934
|
+
v_new_key text;
|
|
935
|
+
v_checked boolean := ${signedIn(ctx)} and current_setting('permdock.sync', true) is distinct from 'on';
|
|
936
|
+
v_allow text[];
|
|
937
|
+
v_deny text[];
|
|
938
|
+
v_include text[];
|
|
939
|
+
begin
|
|
940
|
+
if ${skipped("old")} then
|
|
941
|
+
return null;
|
|
942
|
+
end if;
|
|
943
|
+
if tg_op = 'UPDATE' and not ${skipped("new")} then
|
|
944
|
+
v_new_tenant := ${tenant("new")};
|
|
945
|
+
v_new_scope := ${scope("new")};
|
|
946
|
+
v_new_id := ${id("new")};
|
|
947
|
+
v_new_key := ${rowColumn("new", table.key)}::text;
|
|
948
|
+
if v_new_key = v_old_key
|
|
949
|
+
and v_new_tenant is not distinct from v_old_tenant
|
|
950
|
+
and v_new_scope = v_old_scope
|
|
951
|
+
and v_new_id is not distinct from v_old_id then
|
|
952
|
+
return null;
|
|
953
|
+
end if;
|
|
954
|
+
end if;
|
|
955
|
+
if not exists (select 1 from ${perms} c where ${cascadeMatch("old")})
|
|
956
|
+
and not exists (select 1 from ${includes} c where ${cascadeMatch("old")}) then
|
|
957
|
+
return null;
|
|
958
|
+
end if;
|
|
959
|
+
if v_checked then
|
|
960
|
+
perform ${guard}(v_old_tenant, v_old_scope, v_old_id, v_old_key);
|
|
961
|
+
end if;
|
|
962
|
+
if v_new_key is null then
|
|
963
|
+
perform set_config('permdock.sync', 'on', true);
|
|
964
|
+
perform ${qualified(ctx, CUSTOM_ROLES.trustedRemove)}(v_old_tenant, v_old_scope, v_old_id, v_old_key);
|
|
965
|
+
delete from ${includes} c
|
|
966
|
+
where c.include_role = v_old_key
|
|
967
|
+
and not (v_old_key = any(${sqlTextArray(custom.declared)}));
|
|
968
|
+
perform set_config('permdock.sync', '', true);
|
|
969
|
+
return null;
|
|
970
|
+
end if;
|
|
971
|
+
if exists (select 1 from ${perms} c where ${cascadeMatch("new")})
|
|
972
|
+
or exists (select 1 from ${includes} c where ${cascadeMatch("new")}) then
|
|
973
|
+
${raiseSql(" ", "22023", `'permdock: ' || v_new_key || ' already has grants'`, "role-exists")}
|
|
974
|
+
end if;
|
|
975
|
+
update ${perms} c set tenant_id = v_new_tenant, scope = v_new_scope, scope_id = v_new_id, role = v_new_key where ${cascadeMatch("old")};
|
|
976
|
+
update ${includes} c set tenant_id = v_new_tenant, scope = v_new_scope, scope_id = v_new_id, role = v_new_key where ${cascadeMatch("old")};
|
|
977
|
+
if v_checked then
|
|
978
|
+
perform ${guard}(v_new_tenant, v_new_scope, v_new_id, v_new_key);
|
|
979
|
+
select array_agg(${allowEntryOf}) filter (where c.effect = 'allow'),
|
|
980
|
+
array_agg(c.permission) filter (where c.effect = 'deny')
|
|
981
|
+
into v_allow, v_deny
|
|
982
|
+
from ${perms} c
|
|
983
|
+
where ${cascadeMatch("new")};
|
|
984
|
+
select array_agg(c.include_role) into v_include
|
|
985
|
+
from ${includes} c
|
|
986
|
+
where ${cascadeMatch("new")};
|
|
987
|
+
perform ${entries}(v_new_scope, v_allow, v_deny, v_include);
|
|
988
|
+
end if;
|
|
989
|
+
return null;
|
|
990
|
+
end;
|
|
991
|
+
$$;
|
|
992
|
+
revoke execute on function ${fn}() from public, anon, authenticated;
|
|
993
|
+
create or replace trigger "permdock_custom_role_cascade"
|
|
994
|
+
after update or delete on ${target}
|
|
995
|
+
for each row execute function ${fn}();
|
|
996
|
+
`;
|
|
997
|
+
}
|
|
998
|
+
// src/cli/rls/custom-role-compiled.ts
|
|
999
|
+
/** The event name of a tenant's custom-role version message. */
|
|
1000
|
+
const CUSTOM_ROLES_EVENT = "custom_roles";
|
|
1001
|
+
/** `authz-tenant:<tenant>`, the topic one message per edited tenant goes to. */
|
|
1002
|
+
const CUSTOM_ROLES_TENANT_TOPIC = "authz-tenant:";
|
|
1003
|
+
function tenantMatch(alias) {
|
|
1004
|
+
return `(p_tenant is null and ${alias}.tenant_id is null or ${alias}.tenant_id = p_tenant)`;
|
|
1005
|
+
}
|
|
1006
|
+
function roleMatch(alias) {
|
|
1007
|
+
return `${tenantMatch(alias)} and ${alias}.scope = p_scope and ${alias}.role = p_role`;
|
|
1008
|
+
}
|
|
1009
|
+
function trigger(table, suffix, event, fn) {
|
|
1010
|
+
const name = `permdock_custom_roles_compile_${suffix}_${event}`;
|
|
1011
|
+
return `drop trigger if exists "${name}" on ${table};
|
|
1012
|
+
create trigger "${name}"
|
|
1013
|
+
after ${event} on ${table}
|
|
1014
|
+
${event === "insert" ? "referencing new table as permdock_new" : event === "delete" ? "referencing old table as permdock_old" : "referencing old table as permdock_old new table as permdock_new"}
|
|
1015
|
+
for each statement execute function ${fn}();`;
|
|
1016
|
+
}
|
|
1017
|
+
function touched(source) {
|
|
1018
|
+
return `select array_agg(t.tenant_id), array_agg(t.scope), array_agg(t.role) from (select distinct tenant_id, scope, role from ${source}) t`;
|
|
1019
|
+
}
|
|
1020
|
+
/**
|
|
1021
|
+
* `database` mode: the tables a custom-role edit maintains from statement
|
|
1022
|
+
* triggers, so no policy or read resolves a role at query time.
|
|
1023
|
+
*
|
|
1024
|
+
* - `custom_role_version (tenant_id, version)`: one counter per tenant, and one
|
|
1025
|
+
* row with a null tenant for the shared and platform roles. One edit
|
|
1026
|
+
* statement bumps each tenant it touched once.
|
|
1027
|
+
* - `custom_role_compiled`: one row per stored role (and per instance it is
|
|
1028
|
+
* pinned to), holding the grant keys `permdock_custom_keys` resolves, the
|
|
1029
|
+
* grants in `CustomRole` form and the includes.
|
|
1030
|
+
*
|
|
1031
|
+
* A pinned row merges the rows with no instance, so a probe reads the pinned
|
|
1032
|
+
* row when there is one and the unpinned row otherwise.
|
|
1033
|
+
*/
|
|
1034
|
+
function customRoleCompiledSql(ctx) {
|
|
1035
|
+
const custom = ctx.customRoles;
|
|
1036
|
+
if (custom === void 0 || ctx.authorize !== "database") return "";
|
|
1037
|
+
const tenantType = tenantTypeOf(ctx);
|
|
1038
|
+
const perms = qualified(ctx, CUSTOM_ROLES.permissions);
|
|
1039
|
+
const includes = qualified(ctx, CUSTOM_ROLES.includes);
|
|
1040
|
+
const compiled = qualified(ctx, CUSTOM_ROLES.compiled);
|
|
1041
|
+
const versions = qualified(ctx, CUSTOM_ROLES.versions);
|
|
1042
|
+
const keys = qualified(ctx, CUSTOM_ROLES.keys);
|
|
1043
|
+
const compile = qualified(ctx, CUSTOM_ROLES.compile);
|
|
1044
|
+
const compileFor = qualified(ctx, CUSTOM_ROLES.compileFor);
|
|
1045
|
+
const recompile = qualified(ctx, CUSTOM_ROLES.recompile);
|
|
1046
|
+
const entry = `c.${allowEntry(ctx)}`;
|
|
1047
|
+
const broadcast = custom.broadcast;
|
|
1048
|
+
const send = broadcast === void 0 ? "" : `
|
|
1049
|
+
if to_regprocedure('realtime.send(jsonb, text, text, boolean)') is not null then
|
|
1050
|
+
for r in
|
|
1051
|
+
select v.tenant_id, v.version from ${versions} v
|
|
1052
|
+
where v.tenant_id in (select u from unnest(p_owners) u)
|
|
1053
|
+
or (v.tenant_id is null and exists (select 1 from unnest(p_owners) u where u is null))
|
|
1054
|
+
loop
|
|
1055
|
+
execute pg_catalog.format('select %s($1, $2, $3, true)', pg_catalog.to_regprocedure('realtime.send(jsonb, text, text, boolean)')::oid::regproc) using
|
|
1056
|
+
jsonb_build_object('tenant', r.tenant_id, 'version', r.version),
|
|
1057
|
+
${quoteLiteral(CUSTOM_ROLES_EVENT)}::text,
|
|
1058
|
+
(case when r.tenant_id is null then ${quoteLiteral(broadcast.topic)} else ${quoteLiteral(CUSTOM_ROLES_TENANT_TOPIC)} || r.tenant_id::text end)::text;
|
|
1059
|
+
end loop;
|
|
1060
|
+
end if;`;
|
|
1061
|
+
const handler = (event) => {
|
|
1062
|
+
const fn = qualified(ctx, `${CUSTOM_ROLES.compileStatement}_${event}`);
|
|
1063
|
+
const body = event === "insert" ? touched("permdock_new") : event === "delete" ? touched("permdock_old") : `select array_agg(t.tenant_id), array_agg(t.scope), array_agg(t.role)
|
|
1064
|
+
from (select tenant_id, scope, role from permdock_old union select tenant_id, scope, role from permdock_new) t`;
|
|
1065
|
+
return `create or replace function ${fn}()
|
|
1066
|
+
returns trigger
|
|
1067
|
+
language plpgsql
|
|
1068
|
+
volatile
|
|
1069
|
+
security definer
|
|
1070
|
+
set search_path = ''
|
|
1071
|
+
as $$
|
|
1072
|
+
declare
|
|
1073
|
+
v_owners ${tenantType}[];
|
|
1074
|
+
v_scopes text[];
|
|
1075
|
+
v_roles text[];
|
|
1076
|
+
begin
|
|
1077
|
+
${body}
|
|
1078
|
+
into v_owners, v_scopes, v_roles;
|
|
1079
|
+
perform ${compileFor}(v_owners, v_scopes, v_roles);
|
|
1080
|
+
return null;
|
|
1081
|
+
end;
|
|
1082
|
+
$$;
|
|
1083
|
+
revoke execute on function ${fn}() from public, anon, authenticated;`;
|
|
1084
|
+
};
|
|
1085
|
+
return `-- the compiled custom roles: the keys of each stored role, written when it is saved and read by the policies and by subject_for
|
|
1086
|
+
create table if not exists ${versions} (
|
|
1087
|
+
tenant_id ${tenantType},
|
|
1088
|
+
version bigint not null default 0
|
|
1089
|
+
);
|
|
1090
|
+
-- the row with no tenant counts the shared and platform roles
|
|
1091
|
+
create unique index if not exists ${CUSTOM_ROLES.versions}_key on ${versions} (tenant_id) nulls not distinct;
|
|
1092
|
+
alter table ${versions} enable row level security;
|
|
1093
|
+
revoke all on table ${versions} from anon, authenticated, public;
|
|
1094
|
+
|
|
1095
|
+
create table if not exists ${compiled} (
|
|
1096
|
+
tenant_id ${tenantType},
|
|
1097
|
+
scope text not null,
|
|
1098
|
+
scope_id text,
|
|
1099
|
+
role text not null,
|
|
1100
|
+
grant_keys text[] not null default '{}',
|
|
1101
|
+
grants jsonb not null default '[]'::jsonb,
|
|
1102
|
+
includes text[] not null default '{}',
|
|
1103
|
+
version bigint not null default 0
|
|
1104
|
+
);
|
|
1105
|
+
create unique index if not exists ${CUSTOM_ROLES.compiled}_role_key on ${compiled} (tenant_id, scope, role, scope_id) nulls not distinct;
|
|
1106
|
+
alter table ${compiled} enable row level security;
|
|
1107
|
+
revoke all on table ${compiled} from anon, authenticated, public;
|
|
1108
|
+
|
|
1109
|
+
-- one stored role, compiled: a row per instance it is pinned to, each merged with the rows that name no instance
|
|
1110
|
+
create or replace function ${compile}(p_tenant ${tenantType}, p_scope text, p_role text, p_version bigint)
|
|
1111
|
+
returns void
|
|
1112
|
+
language plpgsql
|
|
1113
|
+
volatile
|
|
1114
|
+
security definer
|
|
1115
|
+
set search_path = ''
|
|
1116
|
+
as $$
|
|
1117
|
+
begin
|
|
1118
|
+
delete from ${compiled} c
|
|
1119
|
+
where (p_tenant is null and c.tenant_id is null or c.tenant_id = p_tenant) and c.scope = p_scope and c.role = p_role;
|
|
1120
|
+
insert into ${compiled} (tenant_id, scope, scope_id, role, grant_keys, grants, includes, version)
|
|
1121
|
+
select p_tenant, p_scope, pin.scope_id, p_role,
|
|
1122
|
+
array(select k from ${keys}(e.allow, e.deny, e.incl, p_scope) k order by 1),
|
|
1123
|
+
own.grants, own.incl, p_version
|
|
1124
|
+
from (
|
|
1125
|
+
select c.scope_id from ${perms} c where ${roleMatch("c")}
|
|
1126
|
+
union
|
|
1127
|
+
select c.scope_id from ${includes} c where ${roleMatch("c")}
|
|
1128
|
+
) pin
|
|
1129
|
+
cross join lateral (
|
|
1130
|
+
select
|
|
1131
|
+
coalesce(array_agg(${entry} order by ${entry}) filter (where c.effect = 'allow'), '{}'::text[]) as allow,
|
|
1132
|
+
coalesce(array_agg(c.permission order by c.permission) filter (where c.effect = 'deny'), '{}'::text[]) as deny,
|
|
1133
|
+
array(
|
|
1134
|
+
select i.include_role from ${includes} i
|
|
1135
|
+
where ${roleMatch("i")} and (i.scope_id is null or i.scope_id = pin.scope_id)
|
|
1136
|
+
order by 1
|
|
1137
|
+
) as incl
|
|
1138
|
+
from ${perms} c
|
|
1139
|
+
where ${roleMatch("c")} and (c.scope_id is null or c.scope_id = pin.scope_id)
|
|
1140
|
+
) e
|
|
1141
|
+
cross join lateral (
|
|
1142
|
+
select
|
|
1143
|
+
coalesce(jsonb_agg(jsonb_strip_nulls(jsonb_build_object(
|
|
1144
|
+
'permission', c.permission, 'effect', c.effect, 'level', to_jsonb(c) ->> 'level'
|
|
1145
|
+
)) order by c.permission, c.effect), '[]'::jsonb) as grants,
|
|
1146
|
+
array(
|
|
1147
|
+
select i.include_role from ${includes} i
|
|
1148
|
+
where ${roleMatch("i")} and i.scope_id is not distinct from pin.scope_id
|
|
1149
|
+
order by 1
|
|
1150
|
+
) as incl
|
|
1151
|
+
from ${perms} c
|
|
1152
|
+
where ${roleMatch("c")} and c.scope_id is not distinct from pin.scope_id
|
|
1153
|
+
) own;
|
|
1154
|
+
end;
|
|
1155
|
+
$$;
|
|
1156
|
+
revoke execute on function ${compile}(${tenantType}, text, text, bigint) from public, anon, authenticated;
|
|
1157
|
+
|
|
1158
|
+
-- the roles a statement touched: one version bump per tenant, then each role compiled at the new version
|
|
1159
|
+
create or replace function ${compileFor}(p_owners ${tenantType}[], p_scopes text[], p_roles text[])
|
|
1160
|
+
returns void
|
|
1161
|
+
language plpgsql
|
|
1162
|
+
volatile
|
|
1163
|
+
security definer
|
|
1164
|
+
set search_path = ''
|
|
1165
|
+
as $$
|
|
1166
|
+
declare
|
|
1167
|
+
r record;
|
|
1168
|
+
begin
|
|
1169
|
+
insert into ${versions} as v (tenant_id, version)
|
|
1170
|
+
select distinct u, 1 from unnest(p_owners) u
|
|
1171
|
+
on conflict (tenant_id) do update set version = v.version + 1;
|
|
1172
|
+
for r in
|
|
1173
|
+
select distinct u.own_id, u.scope, u.role, (
|
|
1174
|
+
select v.version from ${versions} v where v.tenant_id is not distinct from u.own_id
|
|
1175
|
+
) as version
|
|
1176
|
+
from unnest(p_owners, p_scopes, p_roles) u(own_id, scope, role)
|
|
1177
|
+
loop
|
|
1178
|
+
perform ${compile}(r.own_id, r.scope, r.role, r.version);
|
|
1179
|
+
end loop;${send}
|
|
1180
|
+
end;
|
|
1181
|
+
$$;
|
|
1182
|
+
revoke execute on function ${compileFor}(${tenantType}[], text[], text[]) from public, anon, authenticated;
|
|
1183
|
+
|
|
1184
|
+
${handler("insert")}
|
|
1185
|
+
|
|
1186
|
+
${handler("update")}
|
|
1187
|
+
|
|
1188
|
+
${handler("delete")}
|
|
1189
|
+
|
|
1190
|
+
${[perms, includes].map((table, index) => [
|
|
1191
|
+
"insert",
|
|
1192
|
+
"update",
|
|
1193
|
+
"delete"
|
|
1194
|
+
].map((event) => trigger(table, index === 0 ? "permissions" : "includes", event, qualified(ctx, `${CUSTOM_ROLES.compileStatement}_${event}`))).join("\n")).join("\n")}
|
|
1195
|
+
|
|
1196
|
+
-- compiles every stored role again, for the first run after an upgrade or a change to the declared roles
|
|
1197
|
+
create or replace function ${recompile}()
|
|
1198
|
+
returns void
|
|
1199
|
+
language plpgsql
|
|
1200
|
+
volatile
|
|
1201
|
+
security definer
|
|
1202
|
+
set search_path = ''
|
|
1203
|
+
as $$
|
|
1204
|
+
begin
|
|
1205
|
+
delete from ${compiled};
|
|
1206
|
+
perform ${compileFor}(
|
|
1207
|
+
array(select t.tenant_id from (select distinct tenant_id, scope, role from ${perms} union select tenant_id, scope, role from ${includes}) t order by t.tenant_id, t.scope, t.role),
|
|
1208
|
+
array(select t.scope from (select distinct tenant_id, scope, role from ${perms} union select tenant_id, scope, role from ${includes}) t order by t.tenant_id, t.scope, t.role),
|
|
1209
|
+
array(select t.role from (select distinct tenant_id, scope, role from ${perms} union select tenant_id, scope, role from ${includes}) t order by t.tenant_id, t.scope, t.role)
|
|
1210
|
+
);
|
|
1211
|
+
end;
|
|
1212
|
+
$$;
|
|
1213
|
+
revoke execute on function ${recompile}() from public, anon, authenticated;`;
|
|
1214
|
+
}
|
|
1215
|
+
// src/cli/rls/custom-role-guard.ts
|
|
1216
|
+
/** A column of the roles-table row a trigger sees as `new`. */
|
|
1217
|
+
function column(name) {
|
|
1218
|
+
return `new.${quoteIdent(name)}`;
|
|
1219
|
+
}
|
|
1220
|
+
/**
|
|
1221
|
+
* The trigger on the application's roles table (`rls.customRoleWrites.roles`)
|
|
1222
|
+
* that refuses a tenant row named like a declared role (`declared-role`) or
|
|
1223
|
+
* like a shared custom role (`name-taken`). A row the `skip` column marks is a
|
|
1224
|
+
* system role of the tenant and passes. Empty without a tenant column: then no
|
|
1225
|
+
* row is a tenant row.
|
|
1226
|
+
*/
|
|
1227
|
+
function customRoleNameGuardSql(ctx) {
|
|
1228
|
+
const custom = ctx.customRoles;
|
|
1229
|
+
const table = custom?.table;
|
|
1230
|
+
const root = ctx.scopes[0]?.name;
|
|
1231
|
+
if (custom === void 0 || table?.tenant === void 0 || root === void 0) return "";
|
|
1232
|
+
const tenant = `${column(table.tenant)}::${tenantTypeOf(ctx)}`;
|
|
1233
|
+
const skipped = table.skip === void 0 ? "false" : `coalesce(${column(table.skip)}, false)`;
|
|
1234
|
+
const fn = qualified(ctx, CUSTOM_ROLES.nameGuard);
|
|
1235
|
+
const target = quoteTable(qualifySqlTable(table.table));
|
|
1236
|
+
const key = `${column(table.key)}::text`;
|
|
1237
|
+
const scope = rolesTableScope(table, tenant, root, column);
|
|
1238
|
+
return `-- the application's roles table: a tenant row cannot take the name of a declared or a shared role
|
|
1239
|
+
create or replace function ${fn}()
|
|
1240
|
+
returns trigger
|
|
1241
|
+
language plpgsql
|
|
1242
|
+
volatile
|
|
1243
|
+
security definer
|
|
1244
|
+
set search_path = ''
|
|
1245
|
+
as $$
|
|
1246
|
+
begin
|
|
1247
|
+
if ${tenant} is null or ${skipped} then
|
|
1248
|
+
return new;
|
|
1249
|
+
end if;
|
|
1250
|
+
if ${key} = any(${sqlTextArray(custom.declared)}) then
|
|
1251
|
+
${raiseSql(" ", "22023", `'permdock: ' || ${key} || ' is a declared role'`, "declared-role")}
|
|
1252
|
+
end if;
|
|
1253
|
+
if ${qualified(ctx, CUSTOM_ROLES.shared)}(${scope}, ${key}) then
|
|
1254
|
+
${raiseSql(" ", "22023", `'permdock: ' || ${key} || ' is a shared role'`, "name-taken")}
|
|
1255
|
+
end if;
|
|
1256
|
+
return new;
|
|
1257
|
+
end;
|
|
1258
|
+
$$;
|
|
1259
|
+
revoke execute on function ${fn}() from public, anon, authenticated;
|
|
1260
|
+
drop trigger if exists "permdock_custom_role_name_guard" on ${target};
|
|
1261
|
+
create trigger "permdock_custom_role_name_guard"
|
|
1262
|
+
before insert or update on ${target}
|
|
1263
|
+
for each row execute function ${fn}();
|
|
1264
|
+
`;
|
|
1265
|
+
}
|
|
1266
|
+
// src/cli/rls/custom-role-writes.ts
|
|
1267
|
+
function callerFunctionsSql(ctx, custom, root, levelReach, forUser) {
|
|
1268
|
+
const leveled = custom.levels === true;
|
|
1269
|
+
const tenantType = tenantTypeOf(ctx);
|
|
1270
|
+
const volatility = "volatile";
|
|
1271
|
+
const rp = qualified(ctx, "role_permissions");
|
|
1272
|
+
const keys = qualified(ctx, CUSTOM_ROLES.keys);
|
|
1273
|
+
const perms = qualified(ctx, CUSTOM_ROLES.permissions);
|
|
1274
|
+
const includes = qualified(ctx, CUSTOM_ROLES.includes);
|
|
1275
|
+
const shape = qualified(ctx, CUSTOM_ROLES.shape);
|
|
1276
|
+
const beyond = qualified(ctx, forUser ? CUSTOM_ROLES.beyondFor : CUSTOM_ROLES.beyond);
|
|
1277
|
+
const guard = qualified(ctx, forUser ? CUSTOM_ROLES.guardFor : CUSTOM_ROLES.guard);
|
|
1278
|
+
const user = forUser ? "p_user" : subjectIdSql(ctx);
|
|
1279
|
+
const userParam = forUser ? "p_user uuid, " : "";
|
|
1280
|
+
const userArg = forUser ? "uuid, " : "";
|
|
1281
|
+
const userCall = forUser ? "p_user, " : "";
|
|
1282
|
+
const has = (key) => forUser ? `${qualified(ctx, HELPERS.hasFor)}(p_user, ${key})` : `${qualified(ctx, HELPERS.has)}(${key})`;
|
|
1283
|
+
const ids = (helper, arg) => `(select x::text from ${qualified(ctx, helper)}(${arg}) x)`;
|
|
1284
|
+
const permitted = (scope, key) => forUser ? ids(permittedForHelper(scope), `p_user, ${key}`) : ids(permittedIdsHelper(scope), key);
|
|
1285
|
+
const members = (scope) => forUser ? ids(memberForHelper(scope), "p_user") : ids(memberIdsHelper(scope), "");
|
|
1286
|
+
const heldKey = (key) => `(${has(key)}
|
|
1287
|
+
or (p_scope <> 'global'
|
|
1288
|
+
and (p_tenant::text in ${permitted(root, key)}
|
|
1289
|
+
or ${perScope(ctx, (scope) => scope === root ? "false" : `p_scope_id in ${permitted(scope, key)}`)})))`;
|
|
1290
|
+
const holdsAny = (permissions, held) => permissions.length === 0 ? "false" : `exists (
|
|
1291
|
+
select 1 from ${rp} rp
|
|
1292
|
+
where rp.effect = 'allow'
|
|
1293
|
+
and rp.permission = any(${sqlTextArray(permissions)})
|
|
1294
|
+
and ${held("rp.grant_key")}
|
|
1295
|
+
)`;
|
|
1296
|
+
const manageKeys = custom.manage ?? [];
|
|
1297
|
+
const manage = holdsAny(manageKeys, heldKey);
|
|
1298
|
+
const platform = holdsAny(manageKeys, has);
|
|
1299
|
+
const requires = custom.requires === void 0 ? "" : `
|
|
1300
|
+
if not ${holdsAny(custom.requires, heldKey)} then
|
|
1301
|
+
${raiseSql(" ", "42501", `'permdock: the caller may not manage roles in ' || coalesce(p_tenant::text, 'the platform')`, "manage-roles")}
|
|
1302
|
+
end if;`;
|
|
1303
|
+
const reachRows = levelReach.map(([grantKey, level]) => `(${quoteLiteral(grantKey)}, ${quoteLiteral(level)})`).join(", ");
|
|
1304
|
+
const levelCheck = leveled && reachRows !== "" ? `
|
|
1305
|
+
or exists (
|
|
1306
|
+
select 1
|
|
1307
|
+
from reach x
|
|
1308
|
+
where x.grant_key = r.grant_key
|
|
1309
|
+
and not exists (
|
|
1310
|
+
select 1 from held h
|
|
1311
|
+
join reach o on o.grant_key = h.grant_key
|
|
1312
|
+
where h.permission = r.permission and o.level = x.level
|
|
1313
|
+
)
|
|
1314
|
+
)` : "";
|
|
1315
|
+
const reachCte = leveled && reachRows !== "" ? `,
|
|
1316
|
+
reach (grant_key, level) as (values ${reachRows})` : "";
|
|
1317
|
+
const match = `${storedTenant(ctx)} and c.scope = p_scope and (p_scope_id is null and c.scope_id is null or c.scope_id = p_scope_id)`;
|
|
1318
|
+
const memberOf = `p_tenant::text in ${members(root)}
|
|
1319
|
+
or ${perScope(ctx, (scope) => scope === root ? "false" : `p_scope_id in ${members(scope)}`)}`;
|
|
1320
|
+
return {
|
|
1321
|
+
beyond: `-- custom-role writes: the permission keys of a definition the caller may not hand out in the tenant, as assignablePermissions computes them
|
|
1322
|
+
create or replace function ${beyond}(${userParam}p_tenant ${tenantType}, p_scope text, p_scope_id text, p_allow text[], p_deny text[], p_include text[])
|
|
1323
|
+
returns setof text
|
|
1324
|
+
language plpgsql
|
|
1325
|
+
${volatility}
|
|
1326
|
+
security definer
|
|
1327
|
+
set search_path = ''
|
|
1328
|
+
as $$
|
|
1329
|
+
begin
|
|
1330
|
+
if ${manage} then
|
|
1331
|
+
return;
|
|
1332
|
+
end if;
|
|
1333
|
+
return query
|
|
1334
|
+
with resolved as (
|
|
1335
|
+
select distinct rp.permission, k.key as grant_key
|
|
1336
|
+
from ${keys}(p_allow, p_deny, p_include, p_scope) k(key)
|
|
1337
|
+
join ${rp} rp on rp.grant_key = k.key and rp.effect = 'allow'
|
|
1338
|
+
),
|
|
1339
|
+
held as (
|
|
1340
|
+
select distinct rp.permission, rp.grant_key
|
|
1341
|
+
from ${rp} rp
|
|
1342
|
+
where rp.effect = 'allow'
|
|
1343
|
+
and rp.permission in (select r.permission from resolved r)
|
|
1344
|
+
and ${heldKey("rp.grant_key")}
|
|
1345
|
+
)${reachCte}
|
|
1346
|
+
select distinct r.permission
|
|
1347
|
+
from resolved r
|
|
1348
|
+
where not exists (select 1 from held h where h.permission = r.permission)${levelCheck};
|
|
1349
|
+
end;
|
|
1350
|
+
$$;
|
|
1351
|
+
revoke execute on function ${beyond}(${userArg}${tenantType}, text, text, text[], text[], text[]) from public, anon, authenticated;`,
|
|
1352
|
+
guard: `-- a custom role the caller may change: membership of the tenant or the instance (a platform role, or a caller holding a manageRoles permission through a global role, needs none), and authority over the stored definition
|
|
1353
|
+
create or replace function ${guard}(${userParam}p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text)
|
|
1354
|
+
returns void
|
|
1355
|
+
language plpgsql
|
|
1356
|
+
${volatility}
|
|
1357
|
+
security definer
|
|
1358
|
+
set search_path = ''
|
|
1359
|
+
as $$
|
|
1360
|
+
declare
|
|
1361
|
+
v_allow text[];
|
|
1362
|
+
v_deny text[];
|
|
1363
|
+
v_include text[];
|
|
1364
|
+
v_beyond text;
|
|
1365
|
+
begin
|
|
1366
|
+
perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);
|
|
1367
|
+
if not (${signedIn(ctx, user)} and (
|
|
1368
|
+
${platform}
|
|
1369
|
+
or (p_scope <> 'global' and coalesce(${memberOf}, false))
|
|
1370
|
+
)) then
|
|
1371
|
+
${raiseSql(" ", "42501", `'permdock: the caller is not a member of ' || coalesce(p_tenant::text, 'the platform')`, "not-member")}
|
|
1372
|
+
end if;${requires}
|
|
1373
|
+
select array_agg(${allowEntry(ctx)}) filter (where c.effect = 'allow'),
|
|
1374
|
+
array_agg(c.permission) filter (where c.effect = 'deny')
|
|
1375
|
+
into v_allow, v_deny
|
|
1376
|
+
from ${perms} c
|
|
1377
|
+
where ${match} and c.role = p_role;
|
|
1378
|
+
select array_agg(c.include_role) into v_include
|
|
1379
|
+
from ${includes} c
|
|
1380
|
+
where ${match} and c.role = p_role;
|
|
1381
|
+
select string_agg(b, ', ' order by b) into v_beyond
|
|
1382
|
+
from ${beyond}(${userCall}p_tenant, p_scope, p_scope_id, v_allow, v_deny, v_include) b;
|
|
1383
|
+
if v_beyond is not null then
|
|
1384
|
+
${raiseSql(" ", "42501", `'permdock: ' || p_role || ' allows ' || v_beyond || ', which the caller may not hand out'`, "not-assignable-by")}
|
|
1385
|
+
end if;
|
|
1386
|
+
end;
|
|
1387
|
+
$$;
|
|
1388
|
+
revoke execute on function ${guard}(${userArg}${tenantType}, text, text, text) from public, anon, authenticated;`
|
|
1389
|
+
};
|
|
1390
|
+
}
|
|
1391
|
+
/**
|
|
1392
|
+
* The functions an application calls to save, rename and delete a custom role
|
|
1393
|
+
* in \`database\` mode, with the rules of \`validateCustomRole\` and
|
|
1394
|
+
* \`assignablePermissions\`: entries inside the ceiling of the role's scope,
|
|
1395
|
+
* includes naming declared roles, and only permissions and levels the caller
|
|
1396
|
+
* may hand out, for the new definition and the stored one alike. A platform
|
|
1397
|
+
* custom role (\`p_scope = 'global'\`, no tenant) and a shared custom role (no
|
|
1398
|
+
* tenant at a lower scope) are written by a caller who holds a
|
|
1399
|
+
* \`meta.manageRoles\` permission through a global role. The
|
|
1400
|
+
* \`permdock_trusted_*\` variants skip the caller checks and keep the
|
|
1401
|
+
* definition checks; no client role may execute them.
|
|
1402
|
+
*/
|
|
1403
|
+
function customRoleWritesSql(ctx, levelReach) {
|
|
1404
|
+
const custom = ctx.customRoles;
|
|
1405
|
+
const root = ctx.scopes[0]?.name;
|
|
1406
|
+
if (custom === void 0 || ctx.authorize !== "database" || root === void 0) return "";
|
|
1407
|
+
const leveled = custom.levels === true;
|
|
1408
|
+
const tenantType = tenantTypeOf(ctx);
|
|
1409
|
+
const rp = qualified(ctx, "role_permissions");
|
|
1410
|
+
const ceiling = qualified(ctx, CUSTOM_ROLES.ceiling);
|
|
1411
|
+
const perms = qualified(ctx, CUSTOM_ROLES.permissions);
|
|
1412
|
+
const includes = qualified(ctx, CUSTOM_ROLES.includes);
|
|
1413
|
+
const beyond = qualified(ctx, CUSTOM_ROLES.beyond);
|
|
1414
|
+
const guard = qualified(ctx, CUSTOM_ROLES.guard);
|
|
1415
|
+
const shape = qualified(ctx, CUSTOM_ROLES.shape);
|
|
1416
|
+
const entries = qualified(ctx, CUSTOM_ROLES.entries);
|
|
1417
|
+
const problem = qualified(ctx, CUSTOM_ROLES.entryProblem);
|
|
1418
|
+
const renames = Object.entries(custom.renamed ?? {}).toSorted(byKey);
|
|
1419
|
+
const current = (expr) => currentKeyExpr(renames, expr);
|
|
1420
|
+
const known = sqlTextArray([...custom.permissions ?? [], ...renames.map(([former]) => former)]);
|
|
1421
|
+
const caller = callerFunctionsSql(ctx, custom, root, levelReach, false);
|
|
1422
|
+
const match = `(p_tenant is null and c.tenant_id is null or c.tenant_id = p_tenant) and c.scope = p_scope and (p_scope_id is null and c.scope_id is null or c.scope_id = p_scope_id)`;
|
|
1423
|
+
const scopes = sqlTextArray(ctx.scopes.map((scope) => scope.name));
|
|
1424
|
+
const roleName = (param) => `coalesce(${param}, '') = '' or ${param} = any(${sqlTextArray(custom.declared)})`;
|
|
1425
|
+
const levelOf = leveled ? ", nullif(split_part(e, '@', 2), '')" : "";
|
|
1426
|
+
const levelColumn = leveled ? ", level" : "";
|
|
1427
|
+
const sharedRole = qualified(ctx, CUSTOM_ROLES.shared);
|
|
1428
|
+
const taken = (param) => ` if p_tenant is not null and ${sharedRole}(p_scope, ${param}) then
|
|
1429
|
+
${raiseSql(" ", "22023", `'permdock: ' || ${param} || ' is the name of a shared custom role'`, "name-taken")}
|
|
1430
|
+
end if;
|
|
1431
|
+
`;
|
|
1432
|
+
const write = `${taken("p_role")} delete from ${perms} c where ${match} and c.role = p_role;
|
|
1433
|
+
delete from ${includes} c where ${match} and c.role = p_role;
|
|
1434
|
+
insert into ${perms} (tenant_id, scope, scope_id, role, permission, effect${levelColumn})
|
|
1435
|
+
select distinct p_tenant, p_scope, p_scope_id, p_role, ${current(leveled ? "split_part(e, '@', 1)" : "e")}, 'allow'${levelOf}
|
|
1436
|
+
from unnest(coalesce(p_allow, '{}'::text[])) e
|
|
1437
|
+
union
|
|
1438
|
+
select distinct p_tenant, p_scope, p_scope_id, p_role, ${current("e")}, 'deny'${leveled ? ", null" : ""}
|
|
1439
|
+
from unnest(coalesce(p_deny, '{}'::text[])) e;
|
|
1440
|
+
insert into ${includes} (tenant_id, scope, scope_id, role, include_role)
|
|
1441
|
+
select distinct p_tenant, p_scope, p_scope_id, p_role, e
|
|
1442
|
+
from unnest(coalesce(p_include, '{}'::text[])) e;`;
|
|
1443
|
+
const move = `${taken("p_to")} if ${roleName("p_to")} then
|
|
1444
|
+
${raiseSql(" ", "22023", `'permdock: ' || coalesce(p_to, 'null') || ' is not a custom role name'`, "declared-role")}
|
|
1445
|
+
end if;
|
|
1446
|
+
if exists (select 1 from ${perms} c where ${match} and c.role = p_to)
|
|
1447
|
+
or exists (select 1 from ${includes} c where ${match} and c.role = p_to) then
|
|
1448
|
+
${raiseSql(" ", "22023", `'permdock: ' || p_to || ' already has grants'`, "role-exists")}
|
|
1449
|
+
end if;
|
|
1450
|
+
update ${perms} c set role = p_to where ${match} and c.role = p_from;
|
|
1451
|
+
update ${includes} c set role = p_to where ${match} and c.role = p_from;`;
|
|
1452
|
+
const remove = ` delete from ${perms} c where ${match} and c.role = p_role;
|
|
1453
|
+
delete from ${includes} c where ${match} and c.role = p_role;`;
|
|
1454
|
+
const writeArgs = `${tenantType}, text, text, text, text[], text[], text[]`;
|
|
1455
|
+
const renameArgs = `${tenantType}, text, text, text, text`;
|
|
1456
|
+
const removeArgs = `${tenantType}, text, text, text`;
|
|
1457
|
+
const fn = (comment, name, params, args, body, member) => `-- ${comment}
|
|
1458
|
+
create or replace function ${qualified(ctx, name)}(${params})
|
|
1459
|
+
returns void
|
|
1460
|
+
language plpgsql
|
|
1461
|
+
volatile
|
|
1462
|
+
security definer
|
|
1463
|
+
set search_path = ''
|
|
1464
|
+
as $$
|
|
1465
|
+
${body}
|
|
1466
|
+
$$;
|
|
1467
|
+
${member ? `revoke execute on function ${qualified(ctx, name)}(${args}) from public, anon;
|
|
1468
|
+
grant execute on function ${qualified(ctx, name)}(${args}) to authenticated;` : `revoke execute on function ${qualified(ctx, name)}(${args}) from public, anon, authenticated;`}`;
|
|
1469
|
+
const writeParams = `p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text, p_allow text[], p_deny text[], p_include text[]`;
|
|
1470
|
+
const renameParams = `p_tenant ${tenantType}, p_scope text, p_scope_id text, p_from text, p_to text`;
|
|
1471
|
+
const removeParams = `p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text`;
|
|
1472
|
+
return `${caller.beyond}
|
|
1473
|
+
|
|
1474
|
+
-- where a custom role may live: a scope of a tenant, a scope of every tenant (shared: no tenant or instance), or the platform (scope global, no tenant or instance), under an undeclared name
|
|
1475
|
+
create or replace function ${shape}(p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text)
|
|
1476
|
+
returns void
|
|
1477
|
+
language plpgsql
|
|
1478
|
+
stable
|
|
1479
|
+
set search_path = ''
|
|
1480
|
+
as $$
|
|
1481
|
+
begin
|
|
1482
|
+
if p_scope = 'global' then
|
|
1483
|
+
if p_tenant is not null or p_scope_id is not null then
|
|
1484
|
+
${raiseSql(" ", "22023", `'permdock: a platform custom role has no tenant or instance'`, "unknown-scope")}
|
|
1485
|
+
end if;
|
|
1486
|
+
elsif not (p_scope = any(${scopes})) then
|
|
1487
|
+
${raiseSql(" ", "22023", `'permdock: custom roles are held at a scope of a tenant or at global, not ' || coalesce(p_scope, 'null')`, "unknown-scope")}
|
|
1488
|
+
elsif p_tenant is null and p_scope_id is not null then
|
|
1489
|
+
${raiseSql(" ", "22023", `'permdock: a shared custom role has no instance'`, "unknown-scope")}
|
|
1490
|
+
end if;
|
|
1491
|
+
if ${roleName("p_role")} then
|
|
1492
|
+
${raiseSql(" ", "22023", `'permdock: ' || coalesce(p_role, 'null') || ' is not a custom role name'`, "declared-role")}
|
|
1493
|
+
end if;
|
|
1494
|
+
end;
|
|
1495
|
+
$$;
|
|
1496
|
+
revoke execute on function ${shape}(${tenantType}, text, text, text) from public, anon, authenticated;
|
|
1497
|
+
|
|
1498
|
+
${caller.guard}
|
|
1499
|
+
${hasCustomRoleChecksFor(ctx) ? `
|
|
1500
|
+
-- the same checks for a user the caller names: trusted SQL acting later for a stored user; no client role may execute them
|
|
1501
|
+
${callerFunctionsSql(ctx, custom, root, levelReach, true).beyond}
|
|
1502
|
+
|
|
1503
|
+
${callerFunctionsSql(ctx, custom, root, levelReach, true).guard}
|
|
1504
|
+
` : ""}
|
|
1505
|
+
-- null when an allow entry is a declared permission inside the ceiling of the scope${leveled ? ", at a level the resource declares" : ""}; else unknown-permission, outside-ceiling${leveled ? " or unknown-level" : ""}
|
|
1506
|
+
create or replace function ${problem}(p_scope text, p_entry text)
|
|
1507
|
+
returns text
|
|
1508
|
+
language plpgsql
|
|
1509
|
+
stable
|
|
1510
|
+
security definer
|
|
1511
|
+
set search_path = ''
|
|
1512
|
+
as $$
|
|
1513
|
+
declare
|
|
1514
|
+
v_key text := ${current(leveled ? "split_part(p_entry, '@', 1)" : "p_entry")};
|
|
1515
|
+
begin
|
|
1516
|
+
if p_entry is null or not (v_key = any(${known})) then
|
|
1517
|
+
return 'unknown-permission';
|
|
1518
|
+
end if;
|
|
1519
|
+
if not exists (
|
|
1520
|
+
select 1 from ${ceiling} c
|
|
1521
|
+
where c.scope = p_scope and c.effect = 'allow' and ${current("c.permission")} = v_key
|
|
1522
|
+
) then
|
|
1523
|
+
return 'outside-ceiling';
|
|
1524
|
+
end if;${leveled ? `
|
|
1525
|
+
if strpos(p_entry, '@') > 0 and not exists (
|
|
1526
|
+
select 1 from ${ceiling} c
|
|
1527
|
+
where c.scope = p_scope and c.effect = 'allow' and ${current("c.permission")} = v_key
|
|
1528
|
+
and split_part(c.grant_key, '@', 2) = split_part(p_entry, '@', 2)
|
|
1529
|
+
) then
|
|
1530
|
+
return 'unknown-level';
|
|
1531
|
+
end if;` : ""}
|
|
1532
|
+
return null;
|
|
1533
|
+
end;
|
|
1534
|
+
$$;
|
|
1535
|
+
revoke execute on function ${problem}(text, text) from public, anon, authenticated;
|
|
1536
|
+
|
|
1537
|
+
-- the entries of a definition: declared keys and levels inside the ceiling of the scope, and declared includes
|
|
1538
|
+
create or replace function ${entries}(p_scope text, p_allow text[], p_deny text[], p_include text[])
|
|
1539
|
+
returns void
|
|
1540
|
+
language plpgsql
|
|
1541
|
+
stable
|
|
1542
|
+
security definer
|
|
1543
|
+
set search_path = ''
|
|
1544
|
+
as $$
|
|
1545
|
+
declare
|
|
1546
|
+
v_entry text;
|
|
1547
|
+
v_key text;
|
|
1548
|
+
v_problem text;
|
|
1549
|
+
begin
|
|
1550
|
+
foreach v_entry in array coalesce(p_allow, '{}'::text[]) loop
|
|
1551
|
+
v_key := ${current(leveled ? "split_part(v_entry, '@', 1)" : "v_entry")};
|
|
1552
|
+
v_problem := ${problem}(p_scope, v_entry);
|
|
1553
|
+
if v_problem = 'unknown-permission' then
|
|
1554
|
+
${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' is not a declared permission'`, "unknown-permission")}
|
|
1555
|
+
end if;
|
|
1556
|
+
if v_problem = 'outside-ceiling' then
|
|
1557
|
+
${raiseSql(" ", "22023", `'permdock: ' || v_key || ' is outside the ceiling of ' || p_scope`, "outside-ceiling")}
|
|
1558
|
+
end if;${leveled ? `
|
|
1559
|
+
if v_problem = 'unknown-level' then
|
|
1560
|
+
${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' names a level the resource does not declare'`, "unknown-level")}
|
|
1561
|
+
end if;` : ""}
|
|
1562
|
+
end loop;
|
|
1563
|
+
foreach v_entry in array coalesce(p_deny, '{}'::text[]) loop
|
|
1564
|
+
if not (v_entry = any(${known})) then
|
|
1565
|
+
${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' is not a declared permission'`, "unknown-permission")}
|
|
1566
|
+
end if;
|
|
1567
|
+
end loop;
|
|
1568
|
+
foreach v_entry in array coalesce(p_include, '{}'::text[]) loop
|
|
1569
|
+
if not (v_entry = any(${sqlTextArray(custom.declared)})) then
|
|
1570
|
+
${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' is not a declared role'`, "unknown-role")}
|
|
1571
|
+
end if;
|
|
1572
|
+
end loop;
|
|
1573
|
+
select string_agg(distinct ${current("rp.permission")}, ', ') into v_key
|
|
1574
|
+
from ${rp} rp
|
|
1575
|
+
where rp.role = any(coalesce(p_include, '{}'::text[]))
|
|
1576
|
+
and rp.effect = 'allow'
|
|
1577
|
+
and not exists (
|
|
1578
|
+
select 1 from ${ceiling} c
|
|
1579
|
+
where c.scope = p_scope and c.effect = 'allow' and ${current("c.permission")} = ${current("rp.permission")}
|
|
1580
|
+
);
|
|
1581
|
+
if v_key is not null then
|
|
1582
|
+
${raiseSql(" ", "22023", `'permdock: an included role allows ' || v_key || ', outside the ceiling of ' || p_scope`, "outside-ceiling")}
|
|
1583
|
+
end if;
|
|
1584
|
+
end;
|
|
1585
|
+
$$;
|
|
1586
|
+
revoke execute on function ${entries}(text, text[], text[], text[]) from public, anon, authenticated;
|
|
1587
|
+
|
|
1588
|
+
${fn("save a custom role: replace its grants and includes after checking each entry against the ceiling and the caller's own permissions", CUSTOM_ROLES.replace, writeParams, writeArgs, `declare
|
|
1589
|
+
v_beyond text;
|
|
1590
|
+
begin
|
|
1591
|
+
perform ${guard}(p_tenant, p_scope, p_scope_id, p_role);
|
|
1592
|
+
perform ${entries}(p_scope, p_allow, p_deny, p_include);
|
|
1593
|
+
select string_agg(b, ', ' order by b) into v_beyond
|
|
1594
|
+
from ${beyond}(p_tenant, p_scope, p_scope_id, p_allow, p_deny, p_include) b;
|
|
1595
|
+
if v_beyond is not null then
|
|
1596
|
+
${raiseSql(" ", "42501", `'permdock: ' || p_role || ' would allow ' || v_beyond || ', which the caller may not hand out'`, "not-assignable-by")}
|
|
1597
|
+
end if;
|
|
1598
|
+
${write}
|
|
1599
|
+
end;`, true)}
|
|
1600
|
+
|
|
1601
|
+
${fn("rename a custom role: move its grants and includes to the new name", CUSTOM_ROLES.rename, renameParams, renameArgs, `begin
|
|
1602
|
+
perform ${guard}(p_tenant, p_scope, p_scope_id, p_from);
|
|
1603
|
+
${move}
|
|
1604
|
+
end;`, true)}
|
|
1605
|
+
|
|
1606
|
+
${fn("delete a custom role: remove its grants and includes", CUSTOM_ROLES.remove, removeParams, removeArgs, `begin
|
|
1607
|
+
perform ${guard}(p_tenant, p_scope, p_scope_id, p_role);
|
|
1608
|
+
${remove}
|
|
1609
|
+
end;`, true)}
|
|
1610
|
+
|
|
1611
|
+
${fn("save a custom role for a trusted caller (a migration, a job, a backend role granted execute): the definition checks without the caller checks", CUSTOM_ROLES.trustedReplace, writeParams, writeArgs, `begin
|
|
1612
|
+
perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);
|
|
1613
|
+
perform ${entries}(p_scope, p_allow, p_deny, p_include);
|
|
1614
|
+
${write}
|
|
1615
|
+
end;`, false)}
|
|
1616
|
+
|
|
1617
|
+
${fn("rename a custom role for a trusted caller", CUSTOM_ROLES.trustedRename, renameParams, renameArgs, `begin
|
|
1618
|
+
perform ${shape}(p_tenant, p_scope, p_scope_id, p_from);
|
|
1619
|
+
${move}
|
|
1620
|
+
end;`, false)}
|
|
1621
|
+
|
|
1622
|
+
${fn("delete a custom role for a trusted caller", CUSTOM_ROLES.trustedRemove, removeParams, removeArgs, `begin
|
|
1623
|
+
perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);
|
|
1624
|
+
${remove}
|
|
1625
|
+
end;`, false)}`;
|
|
1626
|
+
}
|
|
1627
|
+
// src/cli/rls/global-roles.ts
|
|
1628
|
+
/**
|
|
1629
|
+
* `permdock_replace_global_roles(p_user, p_roles)`: sets the global roles of
|
|
1630
|
+
* one user in `rls.roles` in one statement pair. It runs as the invoker, so the
|
|
1631
|
+
* table's policies and the `rls.assignments` trigger judge every row it deletes
|
|
1632
|
+
* or inserts.
|
|
1633
|
+
*/
|
|
1634
|
+
function globalRolesSql(ctx) {
|
|
1635
|
+
if (ctx.roles === void 0) return "";
|
|
1636
|
+
const source = globalRoleSource(ctx.roles, "public", "t", ctx.customRoles?.table);
|
|
1637
|
+
const table = quoteQualified(ctx.roles.table);
|
|
1638
|
+
const user = quoteIdent(source.user);
|
|
1639
|
+
const fn = qualified(ctx, GLOBAL_ROLES.replace);
|
|
1640
|
+
const type = ctx.dialect === "supabase" ? "uuid" : "text";
|
|
1641
|
+
const wanted = `select distinct r from unnest(coalesce(p_roles, '{}'::text[])) r where r is not null`;
|
|
1642
|
+
const through = source.through;
|
|
1643
|
+
let body;
|
|
1644
|
+
if (through === void 0) {
|
|
1645
|
+
const role = typeof ctx.roles.role === "string" ? ctx.roles.role : "role";
|
|
1646
|
+
const column = quoteIdent(role);
|
|
1647
|
+
body = ` delete from ${table} t
|
|
1648
|
+
where t.${user} = p_user
|
|
1649
|
+
and t.${column}::text <> all(coalesce(p_roles, '{}'::text[]));
|
|
1650
|
+
insert into ${table} (${user}, ${column})
|
|
1651
|
+
select p_user, w.r
|
|
1652
|
+
from (${wanted}) w(r)
|
|
1653
|
+
where not exists (
|
|
1654
|
+
select 1 from ${table} t where t.${user} = p_user and t.${column}::text = w.r
|
|
1655
|
+
);`;
|
|
1656
|
+
} else {
|
|
1657
|
+
const keys = quoteTable(through.table);
|
|
1658
|
+
const id = quoteIdent(through.id);
|
|
1659
|
+
const key = quoteIdent(through.key);
|
|
1660
|
+
const ref = quoteIdent(through.ref);
|
|
1661
|
+
const global = source.tenant === void 0 ? "" : ` and k.${quoteIdent(source.tenant)} is null${source.shared === void 0 ? "" : ` and k.${quoteIdent(source.shared)} is not true`}`;
|
|
1662
|
+
body = ` select string_agg(w.r, ', ' order by w.r) into v_unknown
|
|
1663
|
+
from (${wanted}) w(r)
|
|
1664
|
+
where not exists (select 1 from ${keys} k where k.${key}::text = w.r${global});
|
|
1665
|
+
if v_unknown is not null then
|
|
1666
|
+
raise exception using
|
|
1667
|
+
errcode = '22023',
|
|
1668
|
+
hint = 'unknown-role',
|
|
1669
|
+
message = 'permdock: ' || v_unknown || ' is not a role';
|
|
1670
|
+
end if;
|
|
1671
|
+
delete from ${table} t
|
|
1672
|
+
where t.${user} = p_user
|
|
1673
|
+
and not exists (
|
|
1674
|
+
select 1 from ${keys} k
|
|
1675
|
+
where k.${id} = t.${ref}
|
|
1676
|
+
and k.${key}::text = any(coalesce(p_roles, '{}'::text[]))${global}
|
|
1677
|
+
);
|
|
1678
|
+
insert into ${table} (${user}, ${ref})
|
|
1679
|
+
select p_user, k.${id}
|
|
1680
|
+
from ${keys} k
|
|
1681
|
+
where k.${key}::text in (${wanted})${global}
|
|
1682
|
+
and not exists (
|
|
1683
|
+
select 1 from ${table} t where t.${user} = p_user and t.${ref} = k.${id}
|
|
1684
|
+
);`;
|
|
1685
|
+
}
|
|
1686
|
+
const declare = through === void 0 ? "" : "declare\n v_unknown text;\n";
|
|
1687
|
+
const args = `${type}, text[]`;
|
|
1688
|
+
return `-- set the global roles of a user: delete the others and insert the missing ones, as the caller, so the table's policies and the assignment trigger still apply
|
|
1689
|
+
create or replace function ${fn}(p_user ${type}, p_roles text[])
|
|
1690
|
+
returns void
|
|
1691
|
+
language plpgsql
|
|
1692
|
+
volatile
|
|
1693
|
+
set search_path = ''
|
|
1694
|
+
as $$
|
|
1695
|
+
${declare}begin
|
|
1696
|
+
${body}
|
|
1697
|
+
end;
|
|
1698
|
+
$$;
|
|
1699
|
+
revoke execute on function ${fn}(${args}) from public, anon;
|
|
1700
|
+
grant execute on function ${fn}(${args}) to authenticated;`;
|
|
1701
|
+
}
|
|
1702
|
+
// src/cli/rls/helper-members.ts
|
|
1703
|
+
/**
|
|
1704
|
+
* The body of `member_<scope>_ids()`: instances of `scope` the subject holds a
|
|
1705
|
+
* live membership of, with any role. Not narrowed to the active tenant, and no
|
|
1706
|
+
* cascade: a membership of a child scope is not one of its parent.
|
|
1707
|
+
*/
|
|
1708
|
+
function memberBody(ctx, scope, type, roles) {
|
|
1709
|
+
if (ctx.authorize !== "database") return sqlBody(` select distinct (m ->> 'id')::${type}
|
|
1710
|
+
from (select ${membershipClaim(ctx)} as v) pdk_c
|
|
1711
|
+
cross join lateral jsonb_array_elements(
|
|
1712
|
+
case jsonb_typeof(pdk_c.v) when 'array' then pdk_c.v else '[]'::jsonb end
|
|
1713
|
+
) m
|
|
1714
|
+
where ${signedIn(ctx)}
|
|
1715
|
+
and m ->> 'scope' = ${quoteLiteral(scope)}
|
|
1716
|
+
and m ->> 'id' is not null${keyTenantLine(ctx, scope, claimTenant(ctx, scope))}
|
|
1717
|
+
and jsonb_typeof(m -> 'roles') = 'array'
|
|
1718
|
+
and jsonb_array_length(m -> 'roles') > 0${roles === void 0 ? "" : `\n and (m -> 'roles') ?| ${roles}`}
|
|
1719
|
+
and case jsonb_typeof(m -> 'expires_at')
|
|
1720
|
+
when 'number' then (m ->> 'expires_at')::numeric > extract(epoch from now())
|
|
1721
|
+
else true
|
|
1722
|
+
end${[
|
|
1723
|
+
...claimKeptLines(ctx, " "),
|
|
1724
|
+
...userActive(ctx, " "),
|
|
1725
|
+
...instancesActive(ctx, scope, (name) => name === scope ? `m ->> 'id'` : `m -> 'within' ->> ${quoteLiteral(name)}`, " ")
|
|
1726
|
+
].map((line) => `\n${line}`).join("")}`);
|
|
1727
|
+
return memberRowsBody(ctx, scope, type, subjectIdSql(ctx), scopeSources(ctx, scope), true, roles);
|
|
1728
|
+
}
|
|
1729
|
+
/**
|
|
1730
|
+
* The membership rows of `user` for `scope`, from the sources or else the
|
|
1731
|
+
* mapped table, with the same expiry and suspension filters either way.
|
|
1732
|
+
*/
|
|
1733
|
+
function memberRowsBody(ctx, scope, type, user, sources, keyed = false, roles) {
|
|
1734
|
+
if (sources.length > 0) {
|
|
1735
|
+
const narrow = keyed ? keyTenantLine(ctx, scope, sourceIdOf(scope)(rootName(ctx))) : "";
|
|
1736
|
+
return sourcesBodyOf(` select distinct (ms.id)::${type}
|
|
1737
|
+
from (
|
|
1738
|
+
${sourceRows(sources)}
|
|
1739
|
+
) ms
|
|
1740
|
+
where ${signedIn(ctx, user)}
|
|
1741
|
+
and ms.scope = ${quoteLiteral(scope)}
|
|
1742
|
+
and jsonb_typeof(ms.roles) = 'array'
|
|
1743
|
+
and jsonb_array_length(ms.roles) > 0${roles === void 0 ? "" : `\n and ms.roles ?| ${roles}`}${narrow}${sourceFilters(ctx, scope, user, void 0, sourcesKeep(sources))}`, sources, user);
|
|
1744
|
+
}
|
|
1745
|
+
const mapped = scopeTable(ctx, scope);
|
|
1746
|
+
if (mapped === void 0) return sqlBody(` select null::${type} where false -- no ${scope} memberships table configured`);
|
|
1747
|
+
const { table, column, tenantColumn } = mapped;
|
|
1748
|
+
const role = memberRoleOf(table, "m", " ");
|
|
1749
|
+
const lines = [
|
|
1750
|
+
` select distinct ${memberColumn(column)}::${type}`,
|
|
1751
|
+
` from ${quoteQualified(table.table)} m${role.join}`,
|
|
1752
|
+
` where ${memberColumn(table.user)} = ${user}`,
|
|
1753
|
+
` and ${role.through === void 0 && !role.lateral ? memberColumn(role.column) : role.sql} is not null`
|
|
1754
|
+
];
|
|
1755
|
+
if (roles !== void 0) lines.push(` and (${role.through === void 0 && !role.lateral ? memberColumn(role.column) : role.sql})::text = any(${roles})`);
|
|
1756
|
+
const narrow = keyed ? keyTenantSql(ctx, tenantColumn === void 0 ? void 0 : memberColumn(tenantColumn)) : void 0;
|
|
1757
|
+
if (narrow !== void 0) lines.push(` and ${narrow}`);
|
|
1758
|
+
if (table.expiresAt !== void 0) {
|
|
1759
|
+
const expires = memberColumn(table.expiresAt);
|
|
1760
|
+
lines.push(` and (${expires} is null or ${expires} > now())`);
|
|
1761
|
+
}
|
|
1762
|
+
lines.push(...activeMembershipSql(ctx, disabledColumn(table), void 0).map((part) => ` and ${part}`), ...userActive(ctx, " ", user), ...instancesActive(ctx, scope, (name) => {
|
|
1763
|
+
const held = scopeColumn(table, ctx.scopes, name);
|
|
1764
|
+
return held === void 0 ? void 0 : memberColumn(held);
|
|
1765
|
+
}, " "));
|
|
1766
|
+
return sqlBody(lines.join("\n"));
|
|
1767
|
+
}
|
|
1768
|
+
function membershipClaim(ctx) {
|
|
1769
|
+
const raw = subjectClaimJsonSql(ctx, "memberships");
|
|
1770
|
+
return ctx.dialect === "supabase" ? `coalesce(${raw}, (select auth.jwt()) -> 'app_metadata' -> 'memberships')` : raw;
|
|
1771
|
+
}
|
|
1772
|
+
function memberFunction(ctx, scope, type, anonExecute) {
|
|
1773
|
+
const fn = qualified(ctx, memberIdsHelper(scope));
|
|
1774
|
+
const body = memberBody(ctx, scope, type);
|
|
1775
|
+
const keys = ctx.apiKeys;
|
|
1776
|
+
const keyed = keys === void 0 || scope !== rootName(ctx) ? body : {
|
|
1777
|
+
sql: `${body.sql}\n union\n${serviceKeyMemberSql(ctx, keys, scope, type)}`,
|
|
1778
|
+
vars: body.vars
|
|
1779
|
+
};
|
|
1780
|
+
const grants = anonExecute ? `revoke execute on function ${fn}() from public;
|
|
1781
|
+
grant execute on function ${fn}() to anon, authenticated;` : `revoke execute on function ${fn}() from public, anon;
|
|
1782
|
+
grant execute on function ${fn}() to authenticated;`;
|
|
1783
|
+
return `create or replace function ${fn}()
|
|
1784
|
+
returns setof ${type}
|
|
1785
|
+
${functionBody(keyed, true, true)}
|
|
1786
|
+
${grants}`;
|
|
1787
|
+
}
|
|
1788
|
+
/**
|
|
1789
|
+
* `member_<scope>_ids(p_roles text[])`: `member_<scope>_ids()` narrowed to
|
|
1790
|
+
* memberships holding one of `p_roles` by name, for `rls migrate`'s `role`
|
|
1791
|
+
* helpers. Generated only for a scope such a helper names.
|
|
1792
|
+
*/
|
|
1793
|
+
function memberRolesFunction(ctx, scope, type, anonExecute) {
|
|
1794
|
+
const fn = qualified(ctx, memberIdsHelper(scope));
|
|
1795
|
+
const body = memberBody(ctx, scope, type, "p_roles");
|
|
1796
|
+
const grants = anonExecute ? `revoke execute on function ${fn}(text[]) from public;
|
|
1797
|
+
grant execute on function ${fn}(text[]) to anon, authenticated;` : `revoke execute on function ${fn}(text[]) from public, anon;
|
|
1798
|
+
grant execute on function ${fn}(text[]) to authenticated;`;
|
|
1799
|
+
return `create or replace function ${fn}(p_roles text[])
|
|
1800
|
+
returns setof ${type}
|
|
1801
|
+
${functionBody(body, true, true)}
|
|
1802
|
+
${grants}`;
|
|
1803
|
+
}
|
|
1804
|
+
/**
|
|
1805
|
+
* `member_<scope>_ids_for(p_user uuid)`: `member_<scope>_ids()` for a user the
|
|
1806
|
+
* caller names, read from the membership sources (or the mapped table) in
|
|
1807
|
+
* either mode, so a token hook can call it before any claim exists. Naming the
|
|
1808
|
+
* user is why no client role may execute it. `supabase_auth_admin` may: the
|
|
1809
|
+
* hook's claims functions and better-supabase's `memberIdsFor` call it as that
|
|
1810
|
+
* role. The grant sits next to the function, so no migration order matters, and
|
|
1811
|
+
* runs only where the role exists, so plain Postgres loads the file too. A
|
|
1812
|
+
* `team` or `teams` scope takes `p_active text default null` too, the one
|
|
1813
|
+
* signature the hook's `team_ids` claim calls with the active tenant; its
|
|
1814
|
+
* one-argument form is dropped so a call with the user alone stays
|
|
1815
|
+
* unambiguous.
|
|
1816
|
+
*/
|
|
1817
|
+
function memberForFunction(ctx, scope, type) {
|
|
1818
|
+
const fn = qualified(ctx, memberForHelper(scope));
|
|
1819
|
+
const body = memberRowsBody(ctx, scope, type, "p_user", memberForSources(ctx, scope));
|
|
1820
|
+
const team = ctx.dialect === "supabase" && isTeamScope(scope);
|
|
1821
|
+
const types = team ? "uuid, text" : "uuid";
|
|
1822
|
+
return `${team ? `drop function if exists ${fn}(uuid);\n` : ""}create or replace function ${fn}(p_user uuid${team ? ", p_active text default null" : ""})
|
|
1823
|
+
returns setof ${type}
|
|
1824
|
+
${functionBody(body)}
|
|
1825
|
+
revoke execute on function ${fn}(${types}) from public, anon, authenticated;
|
|
1826
|
+
${authAdminGrants([`grant usage on schema ${quoteIdent(helperSchema(ctx))} to supabase_auth_admin;`, `grant execute on function ${fn}(${types}) to supabase_auth_admin;`])}`;
|
|
1827
|
+
}
|
|
1828
|
+
const AUTH_ADMIN_GUARD = `do $permdock$ begin
|
|
1829
|
+
if exists (select 1 from pg_catalog.pg_roles where rolname = 'supabase_auth_admin') then
|
|
1830
|
+
`;
|
|
1831
|
+
const AUTH_ADMIN_END = ` end if;
|
|
1832
|
+
end
|
|
1833
|
+
$permdock$;`;
|
|
1834
|
+
/** Grants to `supabase_auth_admin` that run only on a database with the role. */
|
|
1835
|
+
function authAdminGrants(grants) {
|
|
1836
|
+
return `${AUTH_ADMIN_GUARD}${grants.map((grant) => ` ${grant}\n`).join("")}${AUTH_ADMIN_END}`;
|
|
1837
|
+
}
|
|
1838
|
+
/**
|
|
1839
|
+
* The `authAdminGrants` blocks of `sql` as plain grants, for a split helpers
|
|
1840
|
+
* file: a declarative schema keeps no `do` block, and Supabase always has the
|
|
1841
|
+
* role.
|
|
1842
|
+
*/
|
|
1843
|
+
function unguardAuthAdminGrants(sql) {
|
|
1844
|
+
let out = "";
|
|
1845
|
+
let from = 0;
|
|
1846
|
+
for (;;) {
|
|
1847
|
+
const start = sql.indexOf(AUTH_ADMIN_GUARD, from);
|
|
1848
|
+
if (start === -1) return out + sql.slice(from);
|
|
1849
|
+
const end = sql.indexOf(AUTH_ADMIN_END, start);
|
|
1850
|
+
const body = sql.slice(start + AUTH_ADMIN_GUARD.length, end);
|
|
1851
|
+
out += sql.slice(from, start);
|
|
1852
|
+
out += body.replaceAll(/^ {4}/gmu, "").trimEnd();
|
|
1853
|
+
from = end + AUTH_ADMIN_END.length;
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
const AUTH_ADMIN_GRANT = /^grant [^;]+ to supabase_auth_admin;$/u;
|
|
1857
|
+
/**
|
|
1858
|
+
* `sql` with its plain grants to `supabase_auth_admin` moved into one
|
|
1859
|
+
* `authAdminGrants` block at the end, for a `--grants-out` file: a migration
|
|
1860
|
+
* may keep a `do` block, and plain Postgres has no such role.
|
|
1861
|
+
*/
|
|
1862
|
+
function guardAuthAdminGrants(sql) {
|
|
1863
|
+
const lines = sql.split("\n");
|
|
1864
|
+
const grants = lines.filter((line) => AUTH_ADMIN_GRANT.test(line));
|
|
1865
|
+
if (grants.length === 0) return sql;
|
|
1866
|
+
const rest = lines.filter((line) => !AUTH_ADMIN_GRANT.test(line)).join("\n");
|
|
1867
|
+
const trailing = /\s*$/u.exec(rest)?.[0] ?? "";
|
|
1868
|
+
return `${rest.trimEnd()}\n${authAdminGrants(grants)}${trailing}`;
|
|
1869
|
+
}
|
|
1870
|
+
/**
|
|
1871
|
+
* `member_<scope>_ids_of(p_user uuid)`: `member_<scope>_ids_for(p_user)` for
|
|
1872
|
+
* the caller only. Any other `p_user` returns no rows, so a client role may
|
|
1873
|
+
* execute it without learning another user's memberships.
|
|
1874
|
+
*/
|
|
1875
|
+
function memberOfFunction(ctx, scope, type) {
|
|
1876
|
+
const fn = qualified(ctx, memberOfHelper(scope));
|
|
1877
|
+
return `create or replace function ${fn}(p_user uuid)
|
|
1878
|
+
returns setof ${type}
|
|
1879
|
+
${functionBody(sqlBody(` select m.id
|
|
1880
|
+
from ${qualified(ctx, memberForHelper(scope))}(p_user) as m(id)
|
|
1881
|
+
where p_user = ${subjectIdSql(ctx)}`))}
|
|
1882
|
+
revoke execute on function ${fn}(uuid) from public, anon;
|
|
1883
|
+
grant execute on function ${fn}(uuid) to authenticated;`;
|
|
1884
|
+
}
|
|
1885
|
+
// src/cli/rls/memo-generation.ts
|
|
1886
|
+
const BUMP = "permdock_bump_memo_generation";
|
|
1887
|
+
const TRIGGER = "permdock_memo_generation";
|
|
1888
|
+
function add(targets, table, columns = []) {
|
|
1889
|
+
const key = qualifySqlTable(table);
|
|
1890
|
+
const existing = targets.get(key);
|
|
1891
|
+
if (existing === void 0) {
|
|
1892
|
+
targets.set(key, {
|
|
1893
|
+
table,
|
|
1894
|
+
columns: columns.length === 0 ? void 0 : new Set(columns)
|
|
1895
|
+
});
|
|
1896
|
+
return;
|
|
1897
|
+
}
|
|
1898
|
+
if (existing.columns === void 0 || columns.length === 0) {
|
|
1899
|
+
targets.set(key, {
|
|
1900
|
+
table: existing.table,
|
|
1901
|
+
columns: void 0
|
|
1902
|
+
});
|
|
1903
|
+
return;
|
|
1904
|
+
}
|
|
1905
|
+
for (const column of columns) existing.columns.add(column);
|
|
1906
|
+
}
|
|
1907
|
+
function suspensionTargets(targets, row) {
|
|
1908
|
+
if (row === void 0) return;
|
|
1909
|
+
const columns = [...row.disabledAt === void 0 ? [] : [row.disabledAt], ...row.status === void 0 ? [] : [row.status]];
|
|
1910
|
+
add(targets, row.table, columns);
|
|
1911
|
+
}
|
|
1912
|
+
const IDENT = String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)`;
|
|
1913
|
+
const READ = new RegExp(String.raw`(?<!\bdistinct\s+)(?<!\bextract\s*\([^()]*)\b(?:from|join)\s+(${IDENT})\.(${IDENT})(?![\w$]|\s*[.(])`, "gu");
|
|
1914
|
+
const SYSTEM = /* @__PURE__ */ new Set([
|
|
1915
|
+
"auth",
|
|
1916
|
+
"pg_catalog",
|
|
1917
|
+
"information_schema"
|
|
1918
|
+
]);
|
|
1919
|
+
function unquote(name) {
|
|
1920
|
+
return name.startsWith("\"") ? name.slice(1, -1).replaceAll("\"\"", "\"") : name;
|
|
1921
|
+
}
|
|
1922
|
+
function readTables(sql) {
|
|
1923
|
+
const out = /* @__PURE__ */ new Set();
|
|
1924
|
+
for (const [, schema = "", table = ""] of sql.matchAll(READ)) {
|
|
1925
|
+
const name = unquote(schema);
|
|
1926
|
+
if (!SYSTEM.has(name)) out.add(`${name}.${unquote(table)}`);
|
|
1927
|
+
}
|
|
1928
|
+
return [...out];
|
|
1929
|
+
}
|
|
1930
|
+
/** A `role_permissions` view cannot carry a trigger. */
|
|
1931
|
+
function memoTable(ctx, table) {
|
|
1932
|
+
return !(ctx.seeds === "view" && qualifySqlTable(table) === `${helperSchema(ctx)}.role_permissions`);
|
|
1933
|
+
}
|
|
1934
|
+
function memoTargets(ctx, reads) {
|
|
1935
|
+
const schema = helperSchema(ctx);
|
|
1936
|
+
const targets = /* @__PURE__ */ new Map();
|
|
1937
|
+
if (memoTable(ctx, `${schema}.role_permissions`)) add(targets, `${schema}.role_permissions`);
|
|
1938
|
+
if (ctx.customRoles !== void 0) {
|
|
1939
|
+
add(targets, `${schema}.${CUSTOM_ROLES.permissions}`);
|
|
1940
|
+
add(targets, `${schema}.${CUSTOM_ROLES.includes}`);
|
|
1941
|
+
const roles = ctx.customRoles.table;
|
|
1942
|
+
if (roles !== void 0) add(targets, roles.table, [
|
|
1943
|
+
roles.key,
|
|
1944
|
+
...roles.tenant === void 0 ? [] : [roles.tenant],
|
|
1945
|
+
...roles.scope === void 0 ? [] : [roles.scope]
|
|
1946
|
+
]);
|
|
1947
|
+
}
|
|
1948
|
+
suspensionTargets(targets, ctx.suspension?.users);
|
|
1949
|
+
for (const row of Object.values(ctx.suspension?.scopes ?? {})) suspensionTargets(targets, row);
|
|
1950
|
+
for (const table of readTables(reads)) if (memoTable(ctx, table) && !targets.has(qualifySqlTable(table))) add(targets, table);
|
|
1951
|
+
if (ctx.seeds === "view") targets.delete(qualifySqlTable(`${schema}.role_permissions`));
|
|
1952
|
+
return targets;
|
|
1953
|
+
}
|
|
1954
|
+
function triggersSql(ctx, targets) {
|
|
1955
|
+
const trigger = qualified(ctx, TRIGGER);
|
|
1956
|
+
return [...targets].map(({ table, columns }) => {
|
|
1957
|
+
const target = quoteTable(qualifySqlTable(table));
|
|
1958
|
+
const update = columns === void 0 ? "update" : `update of ${[...columns].map((column) => quoteIdent(column)).join(", ")}`;
|
|
1959
|
+
return `drop trigger if exists ${quoteIdent(TRIGGER)} on ${target};
|
|
1960
|
+
create trigger ${quoteIdent(TRIGGER)}
|
|
1961
|
+
after insert or ${update} or delete on ${target}
|
|
1962
|
+
for each statement execute function ${trigger}();
|
|
1963
|
+
drop trigger if exists ${quoteIdent(`${TRIGGER}_truncate`)} on ${target};
|
|
1964
|
+
create trigger ${quoteIdent(`${TRIGGER}_truncate`)}
|
|
1965
|
+
after truncate on ${target}
|
|
1966
|
+
for each statement execute function ${trigger}();`;
|
|
1967
|
+
}).join("\n");
|
|
1968
|
+
}
|
|
1969
|
+
/**
|
|
1970
|
+
* The triggers that invalidate the memo when a write changes permitted ids
|
|
1971
|
+
* inside the statement: the permission map, a custom role's grants, a suspended
|
|
1972
|
+
* user or scope, and every table `reads` (the memoized helper bodies) selects
|
|
1973
|
+
* from, such as the membership sources and the global roles. The hook's version
|
|
1974
|
+
* triggers call the same bump.
|
|
1975
|
+
*/
|
|
1976
|
+
function memoGenerationSql(ctx, reads = "") {
|
|
1977
|
+
if (!memoizes(ctx)) return "";
|
|
1978
|
+
const bump = qualified(ctx, BUMP);
|
|
1979
|
+
const trigger = qualified(ctx, TRIGGER);
|
|
1980
|
+
const put = qualified(ctx, "permdock_memo_put");
|
|
1981
|
+
return `-- a permission, custom-role, suspension or membership write changes permitted ids inside the statement
|
|
1982
|
+
create or replace function ${put}(p_key text, p_value text)
|
|
1983
|
+
returns void
|
|
1984
|
+
language sql
|
|
1985
|
+
volatile
|
|
1986
|
+
security definer
|
|
1987
|
+
set search_path = ''
|
|
1988
|
+
as $$
|
|
1989
|
+
select ${memoWriteSql(ctx.memo, "p_key", "p_value")}
|
|
1990
|
+
$$;
|
|
1991
|
+
revoke execute on function ${put}(text, text) from public, anon, authenticated;
|
|
1992
|
+
|
|
1993
|
+
create or replace function ${bump}()
|
|
1994
|
+
returns void
|
|
1995
|
+
language sql
|
|
1996
|
+
volatile
|
|
1997
|
+
security definer
|
|
1998
|
+
set search_path = ''
|
|
1999
|
+
as $$
|
|
2000
|
+
select set_config(
|
|
2001
|
+
'permdock.m.gen',
|
|
2002
|
+
(coalesce(nullif(current_setting('permdock.m.gen', true), ''), '0')::int + 1)::text,
|
|
2003
|
+
true
|
|
2004
|
+
)
|
|
2005
|
+
$$;
|
|
2006
|
+
revoke execute on function ${bump}() from public, anon, authenticated;
|
|
2007
|
+
|
|
2008
|
+
create or replace function ${trigger}()
|
|
2009
|
+
returns trigger
|
|
2010
|
+
language plpgsql
|
|
2011
|
+
volatile
|
|
2012
|
+
security definer
|
|
2013
|
+
set search_path = ''
|
|
2014
|
+
as $$
|
|
2015
|
+
begin
|
|
2016
|
+
perform ${bump}();
|
|
2017
|
+
return null;
|
|
2018
|
+
end;
|
|
2019
|
+
$$;
|
|
2020
|
+
revoke execute on function ${trigger}() from public, anon, authenticated;
|
|
2021
|
+
${triggersSql(ctx, memoTargets(ctx, reads).values())}`;
|
|
2022
|
+
}
|
|
2023
|
+
function memoReadTriggersSql(ctx, reads, covered) {
|
|
2024
|
+
const done = memoTargets(ctx, covered);
|
|
2025
|
+
const targets = /* @__PURE__ */ new Map();
|
|
2026
|
+
for (const table of readTables(reads)) if (memoTable(ctx, table) && !done.has(qualifySqlTable(table))) add(targets, table);
|
|
2027
|
+
return targets.size === 0 ? "" : triggersSql(ctx, targets.values());
|
|
2028
|
+
}
|
|
2029
|
+
// src/cli/rls/set-helpers.ts
|
|
2030
|
+
/**
|
|
2031
|
+
* `permitted_<scope>_id_array(p_grant)`: the ids of a scope a grant key
|
|
2032
|
+
* reaches, as one array.
|
|
2033
|
+
*/
|
|
2034
|
+
function idArrayHelper(scope) {
|
|
2035
|
+
return permittedIdsHelper(scope).replace(/_ids$/u, "_id_array");
|
|
2036
|
+
}
|
|
2037
|
+
/**
|
|
2038
|
+
* `permdock_<root scope>_has(p_grant, p_tenant)`, named after the root scope
|
|
2039
|
+
* (`permdock_tenant_has` for a scope called `tenant`).
|
|
2040
|
+
*/
|
|
2041
|
+
function scopeHasHelper(scope) {
|
|
2042
|
+
return permittedIdsHelper(scope).replace(/^permitted_/u, "permdock_").replace(/_ids$/u, "_has");
|
|
2043
|
+
}
|
|
2044
|
+
/**
|
|
2045
|
+
* `permitted_<scope>_id_array(p_grant)` for one scope: a policy writes
|
|
2046
|
+
* `<column> = any(<array>)`, which an index on the column serves. The root
|
|
2047
|
+
* scope also gets `permdock_<scope>_has(p_grant, p_tenant)`, one membership
|
|
2048
|
+
* test for one tenant that reads the same array.
|
|
2049
|
+
*/
|
|
2050
|
+
function setHelpersSql(ctx, scope, anonExecute) {
|
|
2051
|
+
const type = scopeTypeOf(ctx, scope);
|
|
2052
|
+
const parallel = memoizes(ctx) ? "" : "\nparallel safe";
|
|
2053
|
+
const array = qualified(ctx, idArrayHelper(scope));
|
|
2054
|
+
const grants = (fn, args) => anonExecute ? `revoke execute on function ${fn}(${args}) from public;\ngrant execute on function ${fn}(${args}) to anon, authenticated;` : `revoke execute on function ${fn}(${args}) from public, anon;\ngrant execute on function ${fn}(${args}) to authenticated;`;
|
|
2055
|
+
const chunks = [`-- ${scope} ids a grant key reaches, as one array, for \`<column> = any(...)\`
|
|
2056
|
+
create or replace function ${array}(p_grant text)
|
|
2057
|
+
returns ${type}[]
|
|
2058
|
+
language sql
|
|
2059
|
+
stable
|
|
2060
|
+
security definer
|
|
2061
|
+
cost 1000${parallel}
|
|
2062
|
+
set search_path = ''
|
|
2063
|
+
as $$
|
|
2064
|
+
select coalesce(array_agg(i), '{}'::${type}[]) from ${qualified(ctx, permittedIdsHelper(scope))}(p_grant) i
|
|
2065
|
+
$$;
|
|
2066
|
+
${grants(array, "text")}`];
|
|
2067
|
+
if (rootScope(ctx.scopes) === scope) {
|
|
2068
|
+
const fn = qualified(ctx, scopeHasHelper(scope));
|
|
2069
|
+
chunks.push(`-- whether a grant key reaches one ${scope}
|
|
2070
|
+
create or replace function ${fn}(p_grant text, p_tenant ${type})
|
|
2071
|
+
returns boolean
|
|
2072
|
+
language sql
|
|
2073
|
+
stable
|
|
2074
|
+
security definer
|
|
2075
|
+
cost 1000${parallel}
|
|
2076
|
+
set search_path = ''
|
|
2077
|
+
as $$
|
|
2078
|
+
select p_tenant = any(${array}(p_grant))
|
|
2079
|
+
$$;
|
|
2080
|
+
${grants(fn, `text, ${type}`)}`);
|
|
2081
|
+
}
|
|
2082
|
+
return chunks.join("\n");
|
|
2083
|
+
}
|
|
2084
|
+
// src/cli/rls/token-scopes.ts
|
|
2085
|
+
const TOKEN_SCOPE_ALLOWS = "permdock_token_scope_allows";
|
|
2086
|
+
const TOKEN_SCOPE_MAP = "permdock_token_scope_map";
|
|
2087
|
+
/**
|
|
2088
|
+
* `rls.tokenScopes` as the SQL generator needs it, or `undefined` when it is
|
|
2089
|
+
* off.
|
|
2090
|
+
*/
|
|
2091
|
+
function tokenScopesPlan(setting, policy) {
|
|
2092
|
+
if (setting !== true) return;
|
|
2093
|
+
const permissions = listPermissions(policy.permissions).map((leaf) => ({
|
|
2094
|
+
key: leaf.key,
|
|
2095
|
+
scope: leaf.scope,
|
|
2096
|
+
renamedFrom: formerKeys(leaf),
|
|
2097
|
+
meta: leaf.meta
|
|
2098
|
+
}));
|
|
2099
|
+
return { scopes: delegatedScopeMap(permissions, policy.oauthScopes) };
|
|
2100
|
+
}
|
|
2101
|
+
function tokenScopeAllowsCall(ctx, grant) {
|
|
2102
|
+
return `${qualified(ctx, TOKEN_SCOPE_ALLOWS)}(${grant})`;
|
|
2103
|
+
}
|
|
2104
|
+
/**
|
|
2105
|
+
* The token's scopes as rows of `s(scope)`: a space-separated string or,
|
|
2106
|
+
* outside `guc`, a JSON array.
|
|
2107
|
+
*/
|
|
2108
|
+
function tokenScopeRows(ctx) {
|
|
2109
|
+
if (ctx.dialect === "guc") return `regexp_split_to_table(btrim(coalesce(${subjectClaimSql(ctx, "scope")}, '')), '\\s+') s(scope)`;
|
|
2110
|
+
const scope = subjectClaimJsonSql(ctx, "scope");
|
|
2111
|
+
return `unnest(case jsonb_typeof(${scope})
|
|
2112
|
+
when 'string' then regexp_split_to_array(btrim(${scope} #>> '{}'), '\\s+')
|
|
2113
|
+
when 'array' then array(select jsonb_array_elements_text(${scope}))
|
|
2114
|
+
else '{}'::text[]
|
|
2115
|
+
end) s(scope)`;
|
|
2116
|
+
}
|
|
2117
|
+
/**
|
|
2118
|
+
* `permdock_token_scope_allows(p_grant)`: a delegated token (a `client_id`, or
|
|
2119
|
+
* an `act` that is not a support or impersonation session) reaches a grant key
|
|
2120
|
+
* only when one of its scopes maps to the key's permission. better-supabase's
|
|
2121
|
+
* `cap_allows` reads the same tokens the same way.
|
|
2122
|
+
*/
|
|
2123
|
+
function tokenScopeAllowsSql(ctx, plan, anonExecute) {
|
|
2124
|
+
const fn = qualified(ctx, TOKEN_SCOPE_ALLOWS);
|
|
2125
|
+
const map = qualified(ctx, TOKEN_SCOPE_MAP);
|
|
2126
|
+
const act = subjectClaimJsonSql(ctx, "act");
|
|
2127
|
+
const grants = anonExecute ? `revoke execute on function ${fn}(text) from public;
|
|
2128
|
+
grant execute on function ${fn}(text) to anon, authenticated;` : `revoke execute on function ${fn}(text) from public, anon;
|
|
2129
|
+
grant execute on function ${fn}(text) to authenticated;`;
|
|
2130
|
+
return `create or replace function ${map}()
|
|
2131
|
+
returns jsonb
|
|
2132
|
+
language sql
|
|
2133
|
+
immutable
|
|
2134
|
+
set search_path = ''
|
|
2135
|
+
as $$
|
|
2136
|
+
select ${quoteLiteral(JSON.stringify(plan.scopes))}::jsonb
|
|
2137
|
+
$$;
|
|
2138
|
+
revoke execute on function ${map}() from public, anon, authenticated;
|
|
2139
|
+
|
|
2140
|
+
-- Token scopes: a delegated token holds only the permissions its scope claim maps to; denies always apply, and a token without client_id or an agent act is not limited
|
|
2141
|
+
create or replace function ${fn}(p_grant text)
|
|
2142
|
+
returns boolean
|
|
2143
|
+
language sql
|
|
2144
|
+
stable
|
|
2145
|
+
security definer
|
|
2146
|
+
set search_path = ''
|
|
2147
|
+
as $$
|
|
2148
|
+
select case
|
|
2149
|
+
when coalesce(${subjectClaimSql(ctx, "client_id")}, '') = ''
|
|
2150
|
+
and (${act} is null
|
|
2151
|
+
or ${act} = 'null'::jsonb
|
|
2152
|
+
or (jsonb_typeof(${act}) = 'object'
|
|
2153
|
+
and ${act} ->> 'kind' in ('support', 'impersonation'))) then true
|
|
2154
|
+
when exists (
|
|
2155
|
+
select 1 from ${qualified(ctx, "role_permissions")} rp
|
|
2156
|
+
where rp.grant_key = p_grant and rp.effect = 'deny'
|
|
2157
|
+
) then true
|
|
2158
|
+
else exists (
|
|
2159
|
+
select 1
|
|
2160
|
+
from ${tokenScopeRows(ctx)}
|
|
2161
|
+
where s.scope <> ''
|
|
2162
|
+
and coalesce(${map}() -> s.scope, '[]'::jsonb)
|
|
2163
|
+
? split_part(split_part(p_grant, '#', 1), '@', 1)
|
|
2164
|
+
)
|
|
2165
|
+
end
|
|
2166
|
+
$$;
|
|
2167
|
+
${grants}`;
|
|
2168
|
+
}
|
|
2169
|
+
// src/cli/rls/helpers.ts
|
|
2170
|
+
/**
|
|
2171
|
+
* The policy-side call for a grant key. Every form is uncorrelated, so Postgres
|
|
2172
|
+
* runs the helper once per statement (an InitPlan, or a hashed SubPlan for
|
|
2173
|
+
* `in`), never once per row.
|
|
2174
|
+
*/
|
|
2175
|
+
function accessSql(ctx, scope, grantKey, column, helper) {
|
|
2176
|
+
const key = quoteLiteral(grantKey);
|
|
2177
|
+
if (scope === "global") return `(select ${qualified(ctx, HELPERS.has)}(${key}))`;
|
|
2178
|
+
if (column === void 0) throw configError(`PermDock CLI: ${scope}-scoped grant needs definePolicy({ scopes.${scope} })`);
|
|
2179
|
+
const fn = qualified(ctx, helper ?? permittedIdsHelper(scope));
|
|
2180
|
+
if (ctx.reuseMemo === true && memoizes(ctx)) return `${quoteIdent(column)} in (${memoHitList(scope, key, `${fn}(${key})`, `${memoUserSql(ctx, subjectIdSql(ctx))}::text`, ctx.memo, scopeTypeOf(ctx, scope))})`;
|
|
2181
|
+
return `${quoteIdent(column)} = any(array(select ${fn}(${key})))`;
|
|
2182
|
+
}
|
|
2183
|
+
/**
|
|
2184
|
+
* `permitted_<parent>_ids(p_grant)` for each \`rls.tables\` \`via\`: the parent
|
|
2185
|
+
* rows whose scope instance the grant reaches. \`security definer\`, so the
|
|
2186
|
+
* caller needs no read on the parent, and called uncorrelated like
|
|
2187
|
+
* \`permitted_<scope>_ids\`.
|
|
2188
|
+
*/
|
|
2189
|
+
function viaHelpersSql(ctx, anonExecute) {
|
|
2190
|
+
const done = /* @__PURE__ */ new Set();
|
|
2191
|
+
const chunks = [];
|
|
2192
|
+
for (const via of Object.values(ctx.vias ?? {})) {
|
|
2193
|
+
if (done.has(via.helper)) continue;
|
|
2194
|
+
done.add(via.helper);
|
|
2195
|
+
chunks.push(`-- rows of ${via.table} whose ${via.column} is a ${via.scope} the grant reaches
|
|
2196
|
+
${helperFunction(ctx, via.helper, `setof ${via.type}`, sqlBody(` select p.${quoteIdent(via.id)}
|
|
2197
|
+
from ${quoteQualified(via.table)} p
|
|
2198
|
+
where p.${quoteIdent(via.column)} = any(array(select ${qualified(ctx, permittedIdsHelper(via.scope))}(p_grant)))`), anonExecute)}`);
|
|
2199
|
+
}
|
|
2200
|
+
return chunks;
|
|
2201
|
+
}
|
|
2202
|
+
function userIdSql(ctx, anonExecute) {
|
|
2203
|
+
const fn = userIdHelperSql(ctx);
|
|
2204
|
+
return `-- the caller's user id: the sub of request.jwt.claims, or null when it is empty or absent
|
|
2205
|
+
create or replace function ${fn}()
|
|
2206
|
+
returns uuid
|
|
2207
|
+
language sql
|
|
2208
|
+
stable
|
|
2209
|
+
parallel safe
|
|
2210
|
+
set search_path = ''
|
|
2211
|
+
as $$
|
|
2212
|
+
select nullif(
|
|
2213
|
+
nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub',
|
|
2214
|
+
''
|
|
2215
|
+
)::uuid
|
|
2216
|
+
$$;
|
|
2217
|
+
${anonExecute ? `revoke execute on function ${fn}() from public;
|
|
2218
|
+
grant execute on function ${fn}() to anon, authenticated;` : `revoke execute on function ${fn}() from public, anon;
|
|
2219
|
+
grant execute on function ${fn}() to authenticated;`}`;
|
|
2220
|
+
}
|
|
2221
|
+
function tokenCurrentSql(ctx, anonExecute) {
|
|
2222
|
+
const fn = qualified(ctx, HELPERS.tokenCurrent);
|
|
2223
|
+
const version = qualified(ctx, AUTHZ_VERSION_TABLE);
|
|
2224
|
+
const grants = anonExecute ? `revoke execute on function ${fn}() from public;
|
|
2225
|
+
grant execute on function ${fn}() to anon, authenticated;` : `revoke execute on function ${fn}() from public, anon;
|
|
2226
|
+
grant execute on function ${fn}() to authenticated;`;
|
|
2227
|
+
return `create or replace function ${fn}()
|
|
2228
|
+
returns boolean
|
|
2229
|
+
language plpgsql
|
|
2230
|
+
stable
|
|
2231
|
+
security definer
|
|
2232
|
+
set search_path = ''
|
|
2233
|
+
as $$
|
|
2234
|
+
begin
|
|
2235
|
+
return coalesce((
|
|
2236
|
+
select to_jsonb(v.version) = (c.j -> 'authz_ver')
|
|
2237
|
+
and coalesce(c.j -> 'memberships_truncated', 'false'::jsonb) <> 'true'::jsonb
|
|
2238
|
+
and jsonb_typeof(c.j -> 'memberships') = 'array'
|
|
2239
|
+
from ${version} v
|
|
2240
|
+
cross join (select auth.jwt() as j) c
|
|
2241
|
+
where v.user_id = ${subjectIdSql(ctx)}
|
|
2242
|
+
), false);
|
|
2243
|
+
end;
|
|
2244
|
+
$$;
|
|
2245
|
+
${grants}`;
|
|
2246
|
+
}
|
|
2247
|
+
function helperFunction(ctx, name, returns, body, anonExecute) {
|
|
2248
|
+
const fn = qualified(ctx, name);
|
|
2249
|
+
const grants = anonExecute ? `revoke execute on function ${fn}(text) from public;
|
|
2250
|
+
grant execute on function ${fn}(text) to anon, authenticated;` : `revoke execute on function ${fn}(text) from public, anon;
|
|
2251
|
+
grant execute on function ${fn}(text) to authenticated;`;
|
|
2252
|
+
return `create or replace function ${fn}(p_grant text)
|
|
2253
|
+
returns ${returns}
|
|
2254
|
+
${functionBody(body, !memoizes(ctx), returns.startsWith("setof"))}
|
|
2255
|
+
${grants}`;
|
|
2256
|
+
}
|
|
2257
|
+
/**
|
|
2258
|
+
* `permdock_has_for(p_user, p_grant)` and one
|
|
2259
|
+
* `permitted_<scope>_ids_for(p_user, p_grant)` per scope in `database` mode:
|
|
2260
|
+
* the bodies of `permdock_has` and `permitted_<scope>_ids` with `p_user` for
|
|
2261
|
+
* the signed-in user and no tenant-claim narrowing, since a named user has no
|
|
2262
|
+
* token. For trusted SQL that acts for a stored user (jobs, triggers, approvals
|
|
2263
|
+
* resolved later). Naming the user is why no client role may execute them:
|
|
2264
|
+
* `security definer` callers run them as their owner, and a backend role needs
|
|
2265
|
+
* its own grant.
|
|
2266
|
+
*/
|
|
2267
|
+
function forUserSql(ctx) {
|
|
2268
|
+
if (ctx.authorize !== "database") return "";
|
|
2269
|
+
const forUser = forUserContext(ctx);
|
|
2270
|
+
const type = ctx.dialect === "supabase" ? "uuid" : "text";
|
|
2271
|
+
const fn = (name, returns, body) => {
|
|
2272
|
+
const qualifiedName = qualified(ctx, name);
|
|
2273
|
+
return `create or replace function ${qualifiedName}(p_user ${type}, p_grant text)
|
|
2274
|
+
returns ${returns}
|
|
2275
|
+
${functionBody(body, !memoizes(ctx), returns.startsWith("setof"))}
|
|
2276
|
+
revoke execute on function ${qualifiedName}(${type}, text) from public, anon, authenticated;`;
|
|
2277
|
+
};
|
|
2278
|
+
return [`-- the helpers for a user the caller names: trusted SQL acting for a stored user; no client role may execute them
|
|
2279
|
+
${fn(HELPERS.hasFor, "boolean", sqlBody(hasBody(forUser)))}`, ...ctx.scopes.map((scope) => {
|
|
2280
|
+
const scopeType = scopeTypeOf(ctx, scope.name);
|
|
2281
|
+
return fn(permittedForHelper(scope.name), `setof ${scopeType}`, scopedBody(forUser, scope.name, scopeType));
|
|
2282
|
+
})].join("\n\n");
|
|
2283
|
+
}
|
|
2284
|
+
function userIdType(ctx) {
|
|
2285
|
+
return ctx.dialect === "supabase" ? "uuid not null references auth.users on delete cascade" : "text not null";
|
|
2286
|
+
}
|
|
2287
|
+
/**
|
|
2288
|
+
* The `role_permissions` rows the policy compiles to: an upsert and a delete of
|
|
2289
|
+
* every other row. Data, not schema, so `supabase db diff` drops it from a
|
|
2290
|
+
* declarative schema; `--split ...,seeds` writes it as its own migration.
|
|
2291
|
+
*/
|
|
2292
|
+
function seedSql(ctx, rows) {
|
|
2293
|
+
const table = qualified(ctx, "role_permissions");
|
|
2294
|
+
if (rows.length === 0) return `delete from ${table};`;
|
|
2295
|
+
return `insert into ${table} (role, permission, grant_key, scope, effect) values
|
|
2296
|
+
${rows.map((row) => ` (${[
|
|
2297
|
+
row.role,
|
|
2298
|
+
row.permission,
|
|
2299
|
+
row.grantKey,
|
|
2300
|
+
row.scope,
|
|
2301
|
+
row.effect
|
|
2302
|
+
].map(quoteLiteral).join(", ")})`).join(",\n")}
|
|
2303
|
+
on conflict (role, grant_key, scope) do update
|
|
2304
|
+
set permission = excluded.permission, effect = excluded.effect;
|
|
2305
|
+
delete from ${table}
|
|
2306
|
+
where (role, grant_key, scope) not in (values
|
|
2307
|
+
${rows.map((row) => ` (${[
|
|
2308
|
+
row.role,
|
|
2309
|
+
row.grantKey,
|
|
2310
|
+
row.scope
|
|
2311
|
+
].map(quoteLiteral).join(", ")})`).join(",\n")}
|
|
2312
|
+
);`;
|
|
2313
|
+
}
|
|
2314
|
+
/**
|
|
2315
|
+
* `role_permissions` as a view over the compiled rows (`rls.seeds: 'view'`).
|
|
2316
|
+
* `security_invoker` makes the view read as its caller, so it adds no
|
|
2317
|
+
* privilege; the table's revoke applies to the view the same way.
|
|
2318
|
+
*/
|
|
2319
|
+
function seedViewSql(ctx, rows) {
|
|
2320
|
+
const view = qualified(ctx, "role_permissions");
|
|
2321
|
+
const columns = "role, permission, grant_key, scope, effect";
|
|
2322
|
+
if (ctx.staticGrants === "ref") return seedRefSql(ctx, rows);
|
|
2323
|
+
const body = rows.length === 0 ? `select null::text, null::text, null::text, null::text, null::text where false` : `select * from (values\n${rows.map((row) => ` (${[
|
|
2324
|
+
row.role,
|
|
2325
|
+
row.permission,
|
|
2326
|
+
row.grantKey,
|
|
2327
|
+
row.scope,
|
|
2328
|
+
row.effect
|
|
2329
|
+
].map(quoteLiteral).join(", ")})`).join(",\n")}\n) as v(${columns})`;
|
|
2330
|
+
const sorted = roleKeyMap(rows);
|
|
2331
|
+
const keys = qualified(ctx, "permdock_role_keys");
|
|
2332
|
+
return `-- rls.seeds: 'view': role_permissions is a view, so the rows travel with the schema
|
|
2333
|
+
create or replace view ${view} (${columns}) with (security_invoker = true) as
|
|
2334
|
+
${body};
|
|
2335
|
+
revoke all on table ${view} from anon, authenticated, public;
|
|
2336
|
+
-- the grant keys of each declared role per scope, as a hash lookup where the view's values list is scanned
|
|
2337
|
+
create or replace function ${keys}(p_scope text, p_role text)
|
|
2338
|
+
returns jsonb
|
|
2339
|
+
language sql
|
|
2340
|
+
immutable
|
|
2341
|
+
parallel safe
|
|
2342
|
+
set search_path = ''
|
|
2343
|
+
as $$
|
|
2344
|
+
select ${quoteLiteral(JSON.stringify(sorted))}::jsonb -> p_scope -> p_role
|
|
2345
|
+
$$;
|
|
2346
|
+
revoke execute on function ${keys}(text, text) from public, anon, authenticated;`;
|
|
2347
|
+
}
|
|
2348
|
+
/**
|
|
2349
|
+
* `rls.staticGrants: 'ref'`: `role_permissions` is a view over the policy
|
|
2350
|
+
* bundle whose hash the SQL pins, and `permdock_role_keys` reads the bundle's
|
|
2351
|
+
* lookup. The rows are not in the SQL; \`permdock policy bundle --kind sql\`
|
|
2352
|
+
* loads them. A bundle that is not loaded, or is loaded under another hash,
|
|
2353
|
+
* leaves the view empty and the lookup null, so every static grant denies.
|
|
2354
|
+
*/
|
|
2355
|
+
function seedRefSql(ctx, rows) {
|
|
2356
|
+
const { hash } = policyBundle(rows);
|
|
2357
|
+
const view = qualified(ctx, "role_permissions");
|
|
2358
|
+
const table = qualified(ctx, POLICY_BUNDLE_TABLE);
|
|
2359
|
+
const keys = qualified(ctx, "permdock_role_keys");
|
|
2360
|
+
return `-- rls.staticGrants: 'ref': the static grants are the policy bundle ${hash}, loaded by permdock policy bundle
|
|
2361
|
+
${bundleTableSql(ctx)}
|
|
2362
|
+
create or replace view ${view} (role, permission, grant_key, scope, effect) with (security_invoker = true) as
|
|
2363
|
+
select r.role, r.permission, r.grant_key, r.scope, r.effect
|
|
2364
|
+
from ${table} b
|
|
2365
|
+
cross join lateral jsonb_to_recordset(b.doc -> 'rows') as r(role text, permission text, grant_key text, scope text, effect text)
|
|
2366
|
+
where b.hash = ${quoteLiteral(hash)};
|
|
2367
|
+
revoke all on table ${view} from anon, authenticated, public;
|
|
2368
|
+
create or replace function ${keys}(p_scope text, p_role text)
|
|
2369
|
+
returns jsonb
|
|
2370
|
+
language sql
|
|
2371
|
+
stable
|
|
2372
|
+
parallel safe
|
|
2373
|
+
set search_path = ''
|
|
2374
|
+
as $$
|
|
2375
|
+
select b.doc -> 'roleKeys' -> p_scope -> p_role from ${table} b where b.hash = ${quoteLiteral(hash)}
|
|
2376
|
+
$$;
|
|
2377
|
+
revoke execute on function ${keys}(text, text) from public, anon, authenticated;`;
|
|
2378
|
+
}
|
|
2379
|
+
/**
|
|
2380
|
+
* `<schema>.seed()`: the same upsert and delete as `seedSql`, for a declarative
|
|
2381
|
+
* schema that carries no rows.
|
|
2382
|
+
*/
|
|
2383
|
+
function seedFunctionSql(ctx, rows) {
|
|
2384
|
+
const fn = qualified(ctx, "seed");
|
|
2385
|
+
return `-- rls.seeds: 'function': the role_permissions rows are data, so a declarative diff leaves them out; run select ${fn}(); after each deploy
|
|
2386
|
+
create or replace function ${fn}()
|
|
2387
|
+
returns void
|
|
2388
|
+
language sql
|
|
2389
|
+
volatile
|
|
2390
|
+
security definer
|
|
2391
|
+
set search_path = ''
|
|
2392
|
+
as $permdock$
|
|
2393
|
+
${seedSql(ctx, rows)}
|
|
2394
|
+
$permdock$;
|
|
2395
|
+
revoke execute on function ${fn}() from public, anon, authenticated;`;
|
|
2396
|
+
}
|
|
2397
|
+
/**
|
|
2398
|
+
* The one lookup from a role to its grant keys on a scope, which every helper
|
|
2399
|
+
* body reads through `cross join lateral`. It reads `role_permissions` as its
|
|
2400
|
+
* caller, as the join it replaces did, and pins `search_path` like every
|
|
2401
|
+
* helper. The pin keeps Postgres from inlining it, so each call is a primary
|
|
2402
|
+
* key range read of `role_permissions`.
|
|
2403
|
+
*/
|
|
2404
|
+
function roleGrantKeysSql(ctx) {
|
|
2405
|
+
const fn = qualified(ctx, HELPERS.roleGrantKeys);
|
|
2406
|
+
return `create or replace function ${fn}(p_scope text, p_role text)
|
|
2407
|
+
returns setof text
|
|
2408
|
+
language sql
|
|
2409
|
+
stable
|
|
2410
|
+
parallel safe
|
|
2411
|
+
rows 10
|
|
2412
|
+
set search_path = ''
|
|
2413
|
+
as $$
|
|
2414
|
+
select rp.grant_key from ${qualified(ctx, "role_permissions")} rp where rp.role = p_role and rp.scope = p_scope
|
|
2415
|
+
$$;
|
|
2416
|
+
revoke execute on function ${fn}(text, text) from public, anon, authenticated;`;
|
|
2417
|
+
}
|
|
2418
|
+
/**
|
|
2419
|
+
* `role_permissions`, its seeds, and the three `security definer` helpers with
|
|
2420
|
+
* `search_path = ''`. `execute` goes to `authenticated` only.
|
|
2421
|
+
*/
|
|
2422
|
+
function helpersSql(ctx, rows, options) {
|
|
2423
|
+
const schema = helperSchema(ctx);
|
|
2424
|
+
const s = quoteIdent(schema);
|
|
2425
|
+
const rp = qualified(ctx, "role_permissions");
|
|
2426
|
+
const chunks = [`-- permdock helpers (${ctx.authorize === "database" ? "database: reads the membership and user_roles tables" : "jwt: reads the role and memberships claims"})
|
|
2427
|
+
-- policies call them uncorrelated, so Postgres evaluates each once per statement`];
|
|
2428
|
+
if (schema !== "public") {
|
|
2429
|
+
const anonUsage = options.anonExecute === true || ctx.capabilities === true;
|
|
2430
|
+
chunks.push(`create schema if not exists ${s};\nrevoke all on schema ${s} from public;\ngrant usage on schema ${s} to ${anonUsage ? "anon, authenticated" : "authenticated"};`);
|
|
2431
|
+
}
|
|
2432
|
+
if (ctx.dialect === "supabase") chunks.push(userIdSql(ctx, options.anonExecute === true));
|
|
2433
|
+
if (ctx.claimsFirst === true) chunks.push(tokenCurrentSql(ctx, options.anonExecute === true));
|
|
2434
|
+
if (ctx.seeds === "view") chunks.push(seedViewSql(ctx, rows));
|
|
2435
|
+
else chunks.push(`create table if not exists ${rp} (
|
|
2436
|
+
role text not null,
|
|
2437
|
+
permission text not null,
|
|
2438
|
+
grant_key text not null,
|
|
2439
|
+
scope text not null check (scope ~ '^[a-z][a-z0-9_]*$'),
|
|
2440
|
+
effect text not null default 'allow' check (effect in ('allow', 'deny')),
|
|
2441
|
+
primary key (role, grant_key, scope)
|
|
2442
|
+
);
|
|
2443
|
+
alter table ${rp} enable row level security;
|
|
2444
|
+
revoke all on table ${rp} from anon, authenticated, public;
|
|
2445
|
+
${roleGrantKeysSql(ctx)}`);
|
|
2446
|
+
if (ctx.seeds === "function") chunks.push(seedFunctionSql(ctx, rows));
|
|
2447
|
+
else if (options.withoutSeeds !== true && ctx.seeds !== "view") chunks.push(seedSql(ctx, rows));
|
|
2448
|
+
if (ctx.authorize === "database" && options.userRoles && ctx.roles === void 0) {
|
|
2449
|
+
const ur = qualified(ctx, "user_roles");
|
|
2450
|
+
chunks.push(`create table if not exists ${ur} (
|
|
2451
|
+
user_id ${userIdType(ctx)},
|
|
2452
|
+
role text not null,
|
|
2453
|
+
primary key (user_id, role)
|
|
2454
|
+
);
|
|
2455
|
+
alter table ${ur} enable row level security;
|
|
2456
|
+
revoke all on table ${ur} from anon, authenticated, public;`);
|
|
2457
|
+
}
|
|
2458
|
+
const custom = customRolesSql(ctx);
|
|
2459
|
+
if (custom !== "") chunks.push(custom);
|
|
2460
|
+
const compiled = customRoleCompiledSql(ctx);
|
|
2461
|
+
if (compiled !== "") chunks.push(compiled);
|
|
2462
|
+
const memoGeneration = memoGenerationSql(ctx, memoReadsSql(ctx));
|
|
2463
|
+
if (memoGeneration !== "") chunks.push(memoGeneration);
|
|
2464
|
+
const anon = options.anonExecute === true;
|
|
2465
|
+
const keys = ctx.apiKeys;
|
|
2466
|
+
if (keys !== void 0) chunks.push(apiKeyAllowsSql(ctx, keys, anon));
|
|
2467
|
+
if (ctx.tokenScopes !== void 0) chunks.push(tokenScopeAllowsSql(ctx, ctx.tokenScopes, anon));
|
|
2468
|
+
if (ctx.interactiveOnly !== void 0) chunks.push(interactiveAllowsSql(ctx, ctx.interactiveOnly, anon));
|
|
2469
|
+
const bodies = grantBodies(ctx);
|
|
2470
|
+
chunks.push(helperFunction(ctx, HELPERS.has, "boolean", bodies.has, anon));
|
|
2471
|
+
const capabilities = capabilitiesSql(ctx);
|
|
2472
|
+
if (capabilities !== "") chunks.push(capabilities);
|
|
2473
|
+
for (const scope of ctx.scopes) {
|
|
2474
|
+
const type = scopeTypeOf(ctx, scope.name);
|
|
2475
|
+
chunks.push(helperFunction(ctx, permittedIdsHelper(scope.name), `setof ${type}`, bodies.ids(scope.name), anon));
|
|
2476
|
+
chunks.push(setHelpersSql(ctx, scope.name, anon));
|
|
2477
|
+
chunks.push(memberFunction(ctx, scope.name, type, anon));
|
|
2478
|
+
if (ctx.roleMemberScopes?.includes(scope.name) === true) chunks.push(memberRolesFunction(ctx, scope.name, type, anon));
|
|
2479
|
+
if (hasMemberFor(ctx, scope.name)) chunks.push(memberForFunction(ctx, scope.name, type));
|
|
2480
|
+
if (hasMemberOf(ctx, scope.name)) chunks.push(memberOfFunction(ctx, scope.name, type));
|
|
2481
|
+
}
|
|
2482
|
+
const teamReaders = hookTeamReadersSql(ctx);
|
|
2483
|
+
if (teamReaders !== "") chunks.push(teamReaders);
|
|
2484
|
+
chunks.push(...viaHelpersSql(ctx, anon));
|
|
2485
|
+
const forUser = forUserSql(ctx);
|
|
2486
|
+
if (forUser !== "") chunks.push(forUser);
|
|
2487
|
+
const writes = customRoleWritesSql(ctx, options.levelReach ?? []);
|
|
2488
|
+
if (writes !== "") {
|
|
2489
|
+
chunks.push(writes);
|
|
2490
|
+
const cascade = customRoleCascadeSql(ctx);
|
|
2491
|
+
if (cascade !== "") chunks.push(cascade);
|
|
2492
|
+
const sync = ctx.customRoles?.sync;
|
|
2493
|
+
if (sync !== void 0) chunks.push(sync);
|
|
2494
|
+
const byId = customRoleByIdSql(ctx, options.trustedReaders);
|
|
2495
|
+
if (byId !== "") chunks.push(byId);
|
|
2496
|
+
const nameGuard = customRoleNameGuardSql(ctx);
|
|
2497
|
+
if (nameGuard !== "") chunks.push(nameGuard);
|
|
2498
|
+
}
|
|
2499
|
+
const globalRoles = globalRolesSql(ctx);
|
|
2500
|
+
if (globalRoles !== "") chunks.push(globalRoles);
|
|
2501
|
+
chunks.push(roleReadersSql(ctx, options.permissions, options.trustedReaders));
|
|
2502
|
+
return stampHelpers(`${chunks.join("\n\n")}\n`);
|
|
2503
|
+
}
|
|
2504
|
+
function memoBody(ctx, scope, type, body) {
|
|
2505
|
+
if (!memoizes(ctx)) return body;
|
|
2506
|
+
return {
|
|
2507
|
+
...body,
|
|
2508
|
+
memo: {
|
|
2509
|
+
type,
|
|
2510
|
+
scope,
|
|
2511
|
+
user: memoUserSql(ctx, subjectIdSql(ctx)),
|
|
2512
|
+
...ctx.memo === void 0 ? {} : { api: ctx.memo }
|
|
2513
|
+
}
|
|
2514
|
+
};
|
|
2515
|
+
}
|
|
2516
|
+
function memoReadsSql(ctx) {
|
|
2517
|
+
const bodies = grantBodies(ctx);
|
|
2518
|
+
return [bodies.has.sql, ...ctx.scopes.map((scope) => bodies.ids(scope.name).sql)].join("\n");
|
|
2519
|
+
}
|
|
2520
|
+
function grantBodies(ctx) {
|
|
2521
|
+
const keys = ctx.apiKeys;
|
|
2522
|
+
const scoped = ctx.tokenScopes !== void 0;
|
|
2523
|
+
const interactive = ctx.interactiveOnly !== void 0;
|
|
2524
|
+
const set = ctx.grantSet === true;
|
|
2525
|
+
const ceiling = (grant) => {
|
|
2526
|
+
const calls = [
|
|
2527
|
+
...keys === void 0 ? [] : [apiKeyAllowsCall(ctx, grant)],
|
|
2528
|
+
...scoped ? [tokenScopeAllowsCall(ctx, grant)] : [],
|
|
2529
|
+
...interactive ? [interactiveAllowsCall(ctx, grant)] : []
|
|
2530
|
+
];
|
|
2531
|
+
return calls.length === 0 ? void 0 : calls.join(" and ");
|
|
2532
|
+
};
|
|
2533
|
+
const allows = ceiling(set ? "ids.grant_key" : "p_grant");
|
|
2534
|
+
const keyTenant = keys === void 0 ? "" : ` and ${keyTenantSql(ctx, void 0) ?? "true"}`;
|
|
2535
|
+
const hasAllows = ceiling(set ? "g.grant_key" : "p_grant");
|
|
2536
|
+
return {
|
|
2537
|
+
has: memoBody(ctx, "global", "boolean", sqlBody(hasAllows === void 0 ? hasBody(ctx) : set ? ` select g.grant_key
|
|
2538
|
+
from (
|
|
2539
|
+
${hasBody(ctx)}
|
|
2540
|
+
) g(grant_key)
|
|
2541
|
+
where ${hasAllows}${keyTenant}` : ceilingHasSql(hasBody(ctx), `${hasAllows}${keyTenant}`))),
|
|
2542
|
+
ids: (scope) => {
|
|
2543
|
+
const type = scopeTypeOf(ctx, scope);
|
|
2544
|
+
const body = scopedBody(ctx, scope, type);
|
|
2545
|
+
const sql = allows === void 0 ? body.sql : keys !== void 0 && scope === rootName(ctx) ? `${body.sql}\n union\n${serviceKeyIdsSql(ctx, keys, scope, type)}` : body.sql;
|
|
2546
|
+
return memoBody(ctx, scope, type, allows === void 0 ? {
|
|
2547
|
+
sql,
|
|
2548
|
+
vars: body.vars
|
|
2549
|
+
} : {
|
|
2550
|
+
sql: set ? ` select ids.id, ids.grant_key
|
|
2551
|
+
from (
|
|
2552
|
+
${sql}
|
|
2553
|
+
) ids(id, grant_key)
|
|
2554
|
+
where ${allows}` : ceilingIdsSql(sql, allows),
|
|
2555
|
+
vars: body.vars
|
|
2556
|
+
});
|
|
2557
|
+
}
|
|
2558
|
+
};
|
|
2559
|
+
}
|
|
2560
|
+
function forUserContext(ctx) {
|
|
2561
|
+
const { apiKeys: _apiKeys, tokenScopes: _tokenScopes, interactiveOnly: _interactiveOnly, claimsFirst: _claimsFirst, ...unkeyed } = ctx;
|
|
2562
|
+
return {
|
|
2563
|
+
...unkeyed,
|
|
2564
|
+
subjectId: "p_user",
|
|
2565
|
+
tenants: "all"
|
|
2566
|
+
};
|
|
2567
|
+
}
|
|
2568
|
+
// src/cli/rls/ownership-names.ts
|
|
2569
|
+
/**
|
|
2570
|
+
* Objects the ownership rules add next to the helpers. Names are part of the
|
|
2571
|
+
* SQL contract.
|
|
2572
|
+
*/
|
|
2573
|
+
const OWNERSHIP = {
|
|
2574
|
+
canAssign: "permdock_can_assign",
|
|
2575
|
+
canAssignFor: "permdock_can_assign_for",
|
|
2576
|
+
canAssignAny: "permdock_can_assign_any",
|
|
2577
|
+
canAssignAnyFor: "permdock_can_assign_any_for",
|
|
2578
|
+
holders: "permdock_holders",
|
|
2579
|
+
transferOnly: "permdock_transfer_only"
|
|
2580
|
+
};
|
|
2581
|
+
/** Objects `rls.assignments` adds. Names are part of the SQL contract. */
|
|
2582
|
+
const ASSIGNMENTS = {
|
|
2583
|
+
custom: "permdock_can_assign_custom_role",
|
|
2584
|
+
customFor: "permdock_can_assign_custom_role_for",
|
|
2585
|
+
trigger: "permdock_assignment"
|
|
2586
|
+
};
|
|
2587
|
+
// src/cli/rls/ownership-triggers.ts
|
|
2588
|
+
function objectName(prefix, scope) {
|
|
2589
|
+
return quoteIdent(`${prefix}_${scope}`);
|
|
2590
|
+
}
|
|
2591
|
+
/**
|
|
2592
|
+
* Live holders of `roleExpr` in instance `idExpr`, with the same kind and
|
|
2593
|
+
* expiry rules as the helpers.
|
|
2594
|
+
*/
|
|
2595
|
+
function holdersSql(ctx, table, column, idExpr, role, into) {
|
|
2596
|
+
const roleExpr = typeof role === "string" ? quoteLiteral(role) : role.expr;
|
|
2597
|
+
const held = memberRoleOf(table, "m", " ");
|
|
2598
|
+
const filters = [`m.${quoteIdent(column)} = ${idExpr}`, `${held.sql} = ${roleExpr}`];
|
|
2599
|
+
if (table.expiresAt !== void 0) {
|
|
2600
|
+
const expires = memberColumn(table.expiresAt);
|
|
2601
|
+
filters.push(`(${expires} is null or ${expires} > now())`);
|
|
2602
|
+
}
|
|
2603
|
+
const disabled = disabledColumn(table);
|
|
2604
|
+
if (disabled !== void 0) filters.push(`${disabled} is null`);
|
|
2605
|
+
const via = memberVia(table);
|
|
2606
|
+
const kind = typeof role === "string" ? roleKindSql(ctx, role, via) : kindFilterSql(ctx, roleExpr, via);
|
|
2607
|
+
if (kind !== void 0) filters.push(kind);
|
|
2608
|
+
return `select count(distinct m.${quoteIdent(table.user)}) into ${into}
|
|
2609
|
+
from ${quoteQualified(table.table)} m${held.join}
|
|
2610
|
+
where ${filters.join("\n and ")}`;
|
|
2611
|
+
}
|
|
2612
|
+
/**
|
|
2613
|
+
* `min` and `max` as a deferred constraint trigger: checked at commit, so a
|
|
2614
|
+
* transfer (demote one holder, promote another) passes in one transaction. An
|
|
2615
|
+
* instance with no memberships left is being torn down and skips `min`.
|
|
2616
|
+
*/
|
|
2617
|
+
function holdersTriggerSql(ctx, scope, table, column, counted) {
|
|
2618
|
+
const fn = qualified(ctx, `${OWNERSHIP.holders}_${scope}`);
|
|
2619
|
+
const col = quoteIdent(column);
|
|
2620
|
+
const checks = counted.map((rule) => {
|
|
2621
|
+
const lines = [` select count(*) into v_total from ${quoteQualified(table.table)} m where m.${col} = v_key;`, ` ${holdersSql(ctx, table, column, "v_key", rule.role, "v_count")};`];
|
|
2622
|
+
if (rule.min > 0) lines.push(` if v_total > 0 and v_count < ${String(rule.min)} then
|
|
2623
|
+
raise exception using
|
|
2624
|
+
errcode = '23514',
|
|
2625
|
+
hint = 'last-holder',
|
|
2626
|
+
message = ${quoteLiteral(`permdock: ${scope} `)} || v_id || ${quoteLiteral(` keeps at least ${String(rule.min)} ${rule.role}`)};
|
|
2627
|
+
end if;`);
|
|
2628
|
+
if (rule.max !== void 0) lines.push(` if v_count > ${String(rule.max)} then
|
|
2629
|
+
raise exception using
|
|
2630
|
+
errcode = '23514',
|
|
2631
|
+
hint = 'max-holders',
|
|
2632
|
+
message = ${quoteLiteral(`permdock: ${scope} `)} || v_id || ${quoteLiteral(` has at most ${String(rule.max)} ${rule.role}`)};
|
|
2633
|
+
end if;`);
|
|
2634
|
+
return lines.join("\n");
|
|
2635
|
+
});
|
|
2636
|
+
return `-- ${scope}: holder counts (min / max), checked at commit
|
|
2637
|
+
create or replace function ${fn}()
|
|
2638
|
+
returns trigger
|
|
2639
|
+
language plpgsql
|
|
2640
|
+
security definer
|
|
2641
|
+
set search_path = ''
|
|
2642
|
+
as $$
|
|
2643
|
+
declare
|
|
2644
|
+
v_ids text[] := '{}';
|
|
2645
|
+
v_id text;
|
|
2646
|
+
v_key ${quoteQualified(table.table)}.${col}%type;
|
|
2647
|
+
v_total bigint;
|
|
2648
|
+
v_count bigint;
|
|
2649
|
+
begin
|
|
2650
|
+
if tg_op in ('UPDATE', 'DELETE') then
|
|
2651
|
+
v_ids := v_ids || old.${col}::text;
|
|
2652
|
+
end if;
|
|
2653
|
+
if tg_op in ('INSERT', 'UPDATE') then
|
|
2654
|
+
v_ids := v_ids || new.${col}::text;
|
|
2655
|
+
end if;
|
|
2656
|
+
foreach v_id in array v_ids loop
|
|
2657
|
+
continue when v_id is null;
|
|
2658
|
+
v_key := v_id;
|
|
2659
|
+
${checks.join("\n")}
|
|
2660
|
+
end loop;
|
|
2661
|
+
return null;
|
|
2662
|
+
end;
|
|
2663
|
+
$$;
|
|
2664
|
+
drop trigger if exists ${objectName(OWNERSHIP.holders, scope)} on ${quoteQualified(table.table)};
|
|
2665
|
+
create constraint trigger ${objectName(OWNERSHIP.holders, scope)}
|
|
2666
|
+
after insert or update or delete on ${quoteQualified(table.table)}
|
|
2667
|
+
deferrable initially deferred
|
|
2668
|
+
for each row execute function ${fn}();`;
|
|
2669
|
+
}
|
|
2670
|
+
/**
|
|
2671
|
+
* `transferOnly` as statement triggers over transition tables: a statement that
|
|
2672
|
+
* changes a role's holder count in an instance that had holders before and
|
|
2673
|
+
* still has some after is refused. Creating the first holder and removing the
|
|
2674
|
+
* last (which `min` guards) are not transfers.
|
|
2675
|
+
*/
|
|
2676
|
+
function transferTriggerSql(ctx, scope, table, column, roles) {
|
|
2677
|
+
const fn = qualified(ctx, `${OWNERSHIP.transferOnly}_${scope}`);
|
|
2678
|
+
const col = quoteIdent(column);
|
|
2679
|
+
const list = `array[${roles.map(quoteLiteral).join(", ")}]::text[]`;
|
|
2680
|
+
const rows = (alias, source, delta) => {
|
|
2681
|
+
const role = memberRoleOf(table, alias);
|
|
2682
|
+
return `select ${alias}.${col} as id, ${role.sql} as role, ${delta} as delta from ${source} ${alias}${role.join} where ${role.sql} = any(${list})`;
|
|
2683
|
+
};
|
|
2684
|
+
const loop = (source) => ` for v_change in
|
|
2685
|
+
select c.id, c.role, sum(c.delta) as delta
|
|
2686
|
+
from (${source}) c
|
|
2687
|
+
group by c.id, c.role
|
|
2688
|
+
loop
|
|
2689
|
+
continue when v_change.delta = 0 or v_change.id is null;
|
|
2690
|
+
${holdersSql(ctx, table, column, "v_change.id", { expr: "v_change.role" }, "v_after")};
|
|
2691
|
+
if v_after > 0 and v_after - v_change.delta > 0 then
|
|
2692
|
+
raise exception using
|
|
2693
|
+
errcode = '23514',
|
|
2694
|
+
hint = 'transfer-only',
|
|
2695
|
+
message = 'permdock: ' || v_change.role || ${quoteLiteral(` in ${scope} `)} || v_change.id || ' moves only by transfer';
|
|
2696
|
+
end if;
|
|
2697
|
+
end loop;`;
|
|
2698
|
+
const inserted = rows("n", "permdock_new", "1");
|
|
2699
|
+
const deleted = rows("o", "permdock_old", "-1");
|
|
2700
|
+
const target = quoteQualified(table.table);
|
|
2701
|
+
const trigger = (op) => {
|
|
2702
|
+
const name = quoteIdent(`${OWNERSHIP.transferOnly}_${scope}_${op}`);
|
|
2703
|
+
return `drop trigger if exists ${name} on ${target};
|
|
2704
|
+
create trigger ${name}
|
|
2705
|
+
after ${op} on ${target}
|
|
2706
|
+
referencing ${op === "insert" ? "new table as permdock_new" : op === "delete" ? "old table as permdock_old" : "old table as permdock_old new table as permdock_new"}
|
|
2707
|
+
for each statement execute function ${fn}();`;
|
|
2708
|
+
};
|
|
2709
|
+
return `-- ${scope}: transfer-only roles (${roles.join(", ")}) keep their holder count per statement
|
|
2710
|
+
create or replace function ${fn}()
|
|
2711
|
+
returns trigger
|
|
2712
|
+
language plpgsql
|
|
2713
|
+
security definer
|
|
2714
|
+
set search_path = ''
|
|
2715
|
+
as $$
|
|
2716
|
+
declare
|
|
2717
|
+
v_change record;
|
|
2718
|
+
v_after bigint;
|
|
2719
|
+
begin
|
|
2720
|
+
if tg_op = 'INSERT' then
|
|
2721
|
+
${loop(inserted)}
|
|
2722
|
+
elsif tg_op = 'DELETE' then
|
|
2723
|
+
${loop(deleted)}
|
|
2724
|
+
else
|
|
2725
|
+
${loop(`${inserted} union all ${deleted}`)}
|
|
2726
|
+
end if;
|
|
2727
|
+
return null;
|
|
2728
|
+
end;
|
|
2729
|
+
$$;
|
|
2730
|
+
${trigger("insert")}
|
|
2731
|
+
${trigger("update")}
|
|
2732
|
+
${trigger("delete")}`;
|
|
2733
|
+
}
|
|
2734
|
+
// src/cli/rls/ownership-sources.ts
|
|
2735
|
+
/**
|
|
2736
|
+
* The membership sources holding scope `name`: `undefined` when there are none,
|
|
2737
|
+
* `'not-tables'` when one of them carries no table to put a trigger on.
|
|
2738
|
+
*/
|
|
2739
|
+
function holderSources(ctx, name) {
|
|
2740
|
+
const sources = memberForSources(ctx, name);
|
|
2741
|
+
if (sources.length === 0) return;
|
|
2742
|
+
const held = [];
|
|
2743
|
+
for (const source of sources) {
|
|
2744
|
+
if (source.sql.holders === void 0) return "not-tables";
|
|
2745
|
+
held.push({
|
|
2746
|
+
table: source.sql.table,
|
|
2747
|
+
holders: source.sql.holders
|
|
2748
|
+
});
|
|
2749
|
+
}
|
|
2750
|
+
return held;
|
|
2751
|
+
}
|
|
2752
|
+
function indent(sql, by) {
|
|
2753
|
+
return sql.replaceAll(/^/gmu, by);
|
|
2754
|
+
}
|
|
2755
|
+
/**
|
|
2756
|
+
* Every source's rows of one instance, each compared with its own typed
|
|
2757
|
+
* `v_key_<n>`.
|
|
2758
|
+
*/
|
|
2759
|
+
function sourceRowsOf(scope, sources) {
|
|
2760
|
+
return sources.map((source, index) => indent(source.holders.rows(scope, { id: `v_key_${String(index)}` }), " ")).join("\n union all\n");
|
|
2761
|
+
}
|
|
2762
|
+
function sourceKeys(sources) {
|
|
2763
|
+
return {
|
|
2764
|
+
declare: sources.map((source, index) => ` v_key_${String(index)} ${source.holders.idType};`).join("\n"),
|
|
2765
|
+
assign: (value, by) => sources.map((_, index) => `${by}v_key_${String(index)} := ${value};`).join("\n")
|
|
2766
|
+
};
|
|
2767
|
+
}
|
|
2768
|
+
function regclassOf(table) {
|
|
2769
|
+
return `${quoteLiteral(quoteQualified(table))}::regclass`;
|
|
2770
|
+
}
|
|
2771
|
+
function sourceTables(sources) {
|
|
2772
|
+
return [...new Set(sources.map((source) => quoteQualified(source.table)))];
|
|
2773
|
+
}
|
|
2774
|
+
/**
|
|
2775
|
+
* `min` and `max` over membership sources: the same commit-time check as on a
|
|
2776
|
+
* mapped table, counted over every source of the scope.
|
|
2777
|
+
*/
|
|
2778
|
+
function sourceHoldersTriggerSql(ctx, scope, sources, counted) {
|
|
2779
|
+
const fn = qualified(ctx, `${OWNERSHIP.holders}_${scope}`);
|
|
2780
|
+
const keys = sourceKeys(sources);
|
|
2781
|
+
const rows = sourceRowsOf(scope, sources);
|
|
2782
|
+
const collect = sources.map((source) => ` if tg_relid = ${regclassOf(source.table)} then
|
|
2783
|
+
if tg_op in ('UPDATE', 'DELETE') then
|
|
2784
|
+
v_ids := v_ids || ${source.holders.id(scope, "old")};
|
|
2785
|
+
end if;
|
|
2786
|
+
if tg_op in ('INSERT', 'UPDATE') then
|
|
2787
|
+
v_ids := v_ids || ${source.holders.id(scope, "new")};
|
|
2788
|
+
end if;
|
|
2789
|
+
end if;`);
|
|
2790
|
+
const checks = counted.map((rule) => {
|
|
2791
|
+
const filters = ["h.live", `h.role = ${quoteLiteral(rule.role)}`];
|
|
2792
|
+
const kind = roleKindSql(ctx, rule.role, "h.via");
|
|
2793
|
+
if (kind !== void 0) filters.push(kind);
|
|
2794
|
+
const lines = [` select count(distinct h.user_id) into v_count
|
|
2795
|
+
from (
|
|
2796
|
+
${rows}
|
|
2797
|
+
) h
|
|
2798
|
+
where ${filters.join("\n and ")};`];
|
|
2799
|
+
if (rule.min > 0) lines.push(` if v_total > 0 and v_count < ${String(rule.min)} then
|
|
2800
|
+
raise exception using
|
|
2801
|
+
errcode = '23514',
|
|
2802
|
+
hint = 'last-holder',
|
|
2803
|
+
message = ${quoteLiteral(`permdock: ${scope} `)} || v_id || ${quoteLiteral(` keeps at least ${String(rule.min)} ${rule.role}`)};
|
|
2804
|
+
end if;`);
|
|
2805
|
+
if (rule.max !== void 0) lines.push(` if v_count > ${String(rule.max)} then
|
|
2806
|
+
raise exception using
|
|
2807
|
+
errcode = '23514',
|
|
2808
|
+
hint = 'max-holders',
|
|
2809
|
+
message = ${quoteLiteral(`permdock: ${scope} `)} || v_id || ${quoteLiteral(` has at most ${String(rule.max)} ${rule.role}`)};
|
|
2810
|
+
end if;`);
|
|
2811
|
+
return lines.join("\n");
|
|
2812
|
+
});
|
|
2813
|
+
const triggers = sourceTables(sources).map((table) => `drop trigger if exists ${objectName(OWNERSHIP.holders, scope)} on ${table};
|
|
2814
|
+
create constraint trigger ${objectName(OWNERSHIP.holders, scope)}
|
|
2815
|
+
after insert or update or delete on ${table}
|
|
2816
|
+
deferrable initially deferred
|
|
2817
|
+
for each row execute function ${fn}();`);
|
|
2818
|
+
return `-- ${scope}: holder counts (min / max) over the membership sources, checked at commit
|
|
2819
|
+
create or replace function ${fn}()
|
|
2820
|
+
returns trigger
|
|
2821
|
+
language plpgsql
|
|
2822
|
+
security definer
|
|
2823
|
+
set search_path = ''
|
|
2824
|
+
as $$
|
|
2825
|
+
declare
|
|
2826
|
+
v_ids text[] := '{}';
|
|
2827
|
+
v_id text;
|
|
2828
|
+
${keys.declare}
|
|
2829
|
+
v_total bigint;
|
|
2830
|
+
v_count bigint;
|
|
2831
|
+
begin
|
|
2832
|
+
${collect.join("\n")}
|
|
2833
|
+
foreach v_id in array v_ids loop
|
|
2834
|
+
continue when v_id is null;
|
|
2835
|
+
${keys.assign("v_id", " ")}
|
|
2836
|
+
select count(*) into v_total
|
|
2837
|
+
from (
|
|
2838
|
+
${rows}
|
|
2839
|
+
) h;
|
|
2840
|
+
${checks.join("\n")}
|
|
2841
|
+
end loop;
|
|
2842
|
+
return null;
|
|
2843
|
+
end;
|
|
2844
|
+
$$;
|
|
2845
|
+
${triggers.join("\n")}`;
|
|
2846
|
+
}
|
|
2847
|
+
function collectChangesSql(changed) {
|
|
2848
|
+
return ` v_changes := v_changes || coalesce((select jsonb_agg(to_jsonb(c)) from (${changed}) c), '[]'::jsonb);`;
|
|
2849
|
+
}
|
|
2850
|
+
/**
|
|
2851
|
+
* `transferOnly` over membership sources: each source table's statement
|
|
2852
|
+
* triggers diff its transition tables, and the count after reads every source.
|
|
2853
|
+
*/
|
|
2854
|
+
function sourceTransferTriggerSql(ctx, scope, sources, roles) {
|
|
2855
|
+
const fn = qualified(ctx, `${OWNERSHIP.transferOnly}_${scope}`);
|
|
2856
|
+
const keys = sourceKeys(sources);
|
|
2857
|
+
const list = `array[${roles.map(quoteLiteral).join(", ")}]::text[]`;
|
|
2858
|
+
const kind = kindFilterSql(ctx, "h.role", "h.via");
|
|
2859
|
+
const changes = (source, from, delta) => `select h.id, h.role, ${delta} as delta from (${source.holders.rows(scope, { from }).replaceAll("\n", " ")}) h where h.role = any(${list})`;
|
|
2860
|
+
const branches = sources.map((source) => ` if tg_relid = ${regclassOf(source.table)} then
|
|
2861
|
+
if tg_op in ('INSERT', 'UPDATE') then
|
|
2862
|
+
${collectChangesSql(changes(source, "permdock_new", "1"))}
|
|
2863
|
+
end if;
|
|
2864
|
+
if tg_op in ('UPDATE', 'DELETE') then
|
|
2865
|
+
${collectChangesSql(changes(source, "permdock_old", "-1"))}
|
|
2866
|
+
end if;
|
|
2867
|
+
end if;`);
|
|
2868
|
+
const triggers = sourceTables(sources).flatMap((table) => [
|
|
2869
|
+
"insert",
|
|
2870
|
+
"update",
|
|
2871
|
+
"delete"
|
|
2872
|
+
].map((op) => {
|
|
2873
|
+
const name = quoteIdent(`${OWNERSHIP.transferOnly}_${scope}_${op}`);
|
|
2874
|
+
return `drop trigger if exists ${name} on ${table};
|
|
2875
|
+
create trigger ${name}
|
|
2876
|
+
after ${op} on ${table}
|
|
2877
|
+
referencing ${op === "insert" ? "new table as permdock_new" : op === "delete" ? "old table as permdock_old" : "old table as permdock_old new table as permdock_new"}
|
|
2878
|
+
for each statement execute function ${fn}();`;
|
|
2879
|
+
}));
|
|
2880
|
+
return `-- ${scope}: transfer-only roles (${roles.join(", ")}) keep their holder count per statement, over the membership sources
|
|
2881
|
+
create or replace function ${fn}()
|
|
2882
|
+
returns trigger
|
|
2883
|
+
language plpgsql
|
|
2884
|
+
security definer
|
|
2885
|
+
set search_path = ''
|
|
2886
|
+
as $$
|
|
2887
|
+
declare
|
|
2888
|
+
v_changes jsonb := '[]'::jsonb;
|
|
2889
|
+
v_change record;
|
|
2890
|
+
v_after bigint;
|
|
2891
|
+
${keys.declare}
|
|
2892
|
+
begin
|
|
2893
|
+
${branches.join("\n")}
|
|
2894
|
+
for v_change in
|
|
2895
|
+
select x.id, x.role, sum(x.delta) as delta
|
|
2896
|
+
from jsonb_to_recordset(v_changes) x(id text, role text, delta bigint)
|
|
2897
|
+
group by x.id, x.role
|
|
2898
|
+
loop
|
|
2899
|
+
continue when v_change.delta = 0 or v_change.id is null;
|
|
2900
|
+
${keys.assign("v_change.id", " ")}
|
|
2901
|
+
select count(distinct h.user_id) into v_after
|
|
2902
|
+
from (
|
|
2903
|
+
${sourceRowsOf(scope, sources)}
|
|
2904
|
+
) h
|
|
2905
|
+
where h.live
|
|
2906
|
+
and h.role = v_change.role${kind === void 0 ? "" : `\n and ${kind}`};
|
|
2907
|
+
if v_after > 0 and v_after - v_change.delta > 0 then
|
|
2908
|
+
raise exception using
|
|
2909
|
+
errcode = '23514',
|
|
2910
|
+
hint = 'transfer-only',
|
|
2911
|
+
message = 'permdock: ' || v_change.role || ${quoteLiteral(` in ${scope} `)} || v_change.id || ' moves only by transfer';
|
|
2912
|
+
end if;
|
|
2913
|
+
end loop;
|
|
2914
|
+
return null;
|
|
2915
|
+
end;
|
|
2916
|
+
$$;
|
|
2917
|
+
${triggers.join("\n")}`;
|
|
2918
|
+
}
|
|
2919
|
+
function pairsSql(pairs) {
|
|
2920
|
+
return `values ${pairs.map((pair) => `(${quoteLiteral(pair.assigner)}, ${quoteLiteral(pair.role)})`).join(", ")}`;
|
|
2921
|
+
}
|
|
2922
|
+
/**
|
|
2923
|
+
* Membership rows of the membership sources for scope `name`, each source's
|
|
2924
|
+
* `select` comparing its user column with a variable `user` names.
|
|
2925
|
+
*/
|
|
2926
|
+
function sourceRowsSql(sources, user) {
|
|
2927
|
+
const keep = sources.some((source) => source.sql.keeps);
|
|
2928
|
+
return sources.map((source) => source.sql.select(user(source), keep).replaceAll(/^/gmu, " ")).join("\n union all\n");
|
|
2929
|
+
}
|
|
2930
|
+
// src/cli/rls/permission-keys.ts
|
|
2931
|
+
/**
|
|
2932
|
+
* The helpers that take a permission key instead of a grant key. Names are part
|
|
2933
|
+
* of the SQL contract.
|
|
2934
|
+
*/
|
|
2935
|
+
const PERMISSION_HELPERS = {
|
|
2936
|
+
grantKeys: "grant_keys",
|
|
2937
|
+
has: "permdock_has_permission",
|
|
2938
|
+
hasFor: "permdock_has_permission_for"
|
|
2939
|
+
};
|
|
2940
|
+
/**
|
|
2941
|
+
* `permitted_<scope>_permission_keys(p_id)`: every permission key the subject
|
|
2942
|
+
* holds on one instance.
|
|
2943
|
+
*/
|
|
2944
|
+
function permissionKeysHelper(scope) {
|
|
2945
|
+
permittedIdsHelper(scope);
|
|
2946
|
+
return `permitted_${scope}_permission_keys`;
|
|
2947
|
+
}
|
|
2948
|
+
/**
|
|
2949
|
+
* `permitted_<scope>_permission_keys_for(p_user, p_id)`, written in `database`
|
|
2950
|
+
* mode.
|
|
2951
|
+
*/
|
|
2952
|
+
function permissionKeysForHelper(scope) {
|
|
2953
|
+
return `${permissionKeysHelper(scope)}_for`;
|
|
2954
|
+
}
|
|
2955
|
+
/** `permitted_<scope>_ids_by_permission(p_permission)`. */
|
|
2956
|
+
function permittedByPermissionHelper(scope) {
|
|
2957
|
+
return `${permittedIdsHelper(scope)}_by_permission`;
|
|
2958
|
+
}
|
|
2959
|
+
/**
|
|
2960
|
+
* A grant's `requires` as SQL: the subject holds `key` globally, or on the
|
|
2961
|
+
* row's instance of a scope that partitions it, through the helpers by
|
|
2962
|
+
* permission key, as `requirementCondition` does in process.
|
|
2963
|
+
*/
|
|
2964
|
+
function requiresSql(ctx, key, resource) {
|
|
2965
|
+
const literal = quoteLiteral(key);
|
|
2966
|
+
return `(${[`(select ${qualified(ctx, PERMISSION_HELPERS.has)}(${literal}))`, ...(resource === void 0 ? [] : partitionsOf(resource, ctx.scopes)).map((scope) => {
|
|
2967
|
+
const field = scopeField(resource, scope, ctx.scopes) ?? scope;
|
|
2968
|
+
return `${quoteIdent(field)} = any(array(select ${qualified(ctx, checkName(permittedByPermissionHelper(scope)))}(${literal})))`;
|
|
2969
|
+
})].join(" or ")})`;
|
|
2970
|
+
}
|
|
2971
|
+
/**
|
|
2972
|
+
* Postgres truncates an identifier past 63 bytes, which would merge two
|
|
2973
|
+
* helpers.
|
|
2974
|
+
*/
|
|
2975
|
+
function checkName(name) {
|
|
2976
|
+
if (new TextEncoder().encode(name).length > 63) throw configError(`PermDock CLI: the helper name ${name} is longer than 63 bytes; use a shorter scope name`);
|
|
2977
|
+
return name;
|
|
2978
|
+
}
|
|
2979
|
+
function grantsFunction(ctx, grants, renamed, anonExecute) {
|
|
2980
|
+
const fn = qualified(ctx, PERMISSION_HELPERS.grantKeys);
|
|
2981
|
+
const map = Object.fromEntries([...grants].toSorted(byKey));
|
|
2982
|
+
const current = Object.keys(renamed).length === 0 ? "p_permission" : `coalesce(${quoteLiteral(JSON.stringify(renamed))}::jsonb ->> p_permission, p_permission)`;
|
|
2983
|
+
return `-- the grant keys a permission key reaches on one scope: its unconditional allows, with p_effect 'deny' every deny, and with 'conditioned-allow' or 'conditioned-deny' the allows or denies that carry a row condition
|
|
2984
|
+
create or replace function ${fn}(p_permission text, p_scope text, p_effect text default 'allow')
|
|
2985
|
+
returns setof text
|
|
2986
|
+
language sql
|
|
2987
|
+
stable
|
|
2988
|
+
set search_path = ''
|
|
2989
|
+
as $$
|
|
2990
|
+
select g.grant_key
|
|
2991
|
+
from pg_catalog.jsonb_array_elements_text(coalesce(
|
|
2992
|
+
${quoteLiteral(JSON.stringify(map))}::jsonb -> p_scope -> ${current} -> p_effect,
|
|
2993
|
+
'[]'::jsonb
|
|
2994
|
+
)) g(grant_key)
|
|
2995
|
+
$$;
|
|
2996
|
+
${grantsSql(fn, "text, text, text", anonExecute)}`;
|
|
2997
|
+
}
|
|
2998
|
+
function grantsSql(fn, args, anonExecute) {
|
|
2999
|
+
return anonExecute ? `revoke execute on function ${fn}(${args}) from public;
|
|
3000
|
+
grant execute on function ${fn}(${args}) to anon, authenticated;` : `revoke execute on function ${fn}(${args}) from public, anon;
|
|
3001
|
+
grant execute on function ${fn}(${args}) to authenticated;`;
|
|
3002
|
+
}
|
|
3003
|
+
function definerSql(fn, params, returns, sql, parallelSafe) {
|
|
3004
|
+
return `create or replace function ${fn}(${params})
|
|
3005
|
+
returns ${returns}
|
|
3006
|
+
language sql
|
|
3007
|
+
stable
|
|
3008
|
+
security definer
|
|
3009
|
+
cost 1000${returns.startsWith("setof") ? "\nrows 10" : ""}${parallelSafe ? "\nparallel safe" : ""}
|
|
3010
|
+
set search_path = ''
|
|
3011
|
+
as $$
|
|
3012
|
+
${sql}
|
|
3013
|
+
$$;`;
|
|
3014
|
+
}
|
|
3015
|
+
function heldSql(at, effect) {
|
|
3016
|
+
return `select 1 from pdk_h where pdk_h.key = pdk_k.key and pdk_h.scope = ${quoteLiteral(at)} and pdk_h.effect = '${effect}'`;
|
|
3017
|
+
}
|
|
3018
|
+
function keysFunction(fn, params, body, access, parallelSafe) {
|
|
3019
|
+
return `create or replace function ${fn}(${params})
|
|
3020
|
+
returns setof text
|
|
3021
|
+
${functionBody(body, parallelSafe).replace("set search_path = ''", "set search_path = ''\nset jit = off")}
|
|
3022
|
+
${access}`;
|
|
3023
|
+
}
|
|
3024
|
+
/**
|
|
3025
|
+
* The permission-key forms of the helpers: `grant_keys`, which maps a
|
|
3026
|
+
* permission key to the grant keys of its unconditional allows on a scope (or
|
|
3027
|
+
* every deny key, or the conditioned allow or deny keys),
|
|
3028
|
+
* `permdock_has_permission(p_permission)` and one
|
|
3029
|
+
* `permitted_<scope>_ids_by_permission(p_permission)` per scope, plus their
|
|
3030
|
+
* `_for(p_user, ...)` forms in `database` mode. They answer with the
|
|
3031
|
+
* unconditional allows minus any deny, so a permission whose allows all carry a
|
|
3032
|
+
* row condition answers nothing. The
|
|
3033
|
+
* `permitted_<scope>_ids_by_permission(p_permission, p_conditioned)` overload
|
|
3034
|
+
* with `true` also lists the instances a conditioned allow reaches and
|
|
3035
|
+
* subtracts only unconditional denies, leaving the row condition to the caller,
|
|
3036
|
+
* as `permittedIds(..., { conditioned: true })` does in process.
|
|
3037
|
+
*/
|
|
3038
|
+
function permissionHelpersSql(ctx, grants, renamed, anonExecute) {
|
|
3039
|
+
const parallel = !memoizes(ctx);
|
|
3040
|
+
const definer = (fn, params, returns, sql) => definerSql(fn, params, returns, sql, parallel);
|
|
3041
|
+
const keys = qualified(ctx, PERMISSION_HELPERS.grantKeys);
|
|
3042
|
+
const allowKeys = (scope) => `${keys}(p_permission, ${quoteLiteral(scope)}) g(grant_key)`;
|
|
3043
|
+
const denyKeys = (scope) => `${keys}(p_permission, ${quoteLiteral(scope)}, 'deny') g(grant_key)`;
|
|
3044
|
+
const has = (helper, user) => ` select exists (select 1 from ${allowKeys("global")} where ${helper}(${user}g.grant_key))
|
|
3045
|
+
and not exists (select 1 from ${denyKeys("global")} where ${helper}(${user}g.grant_key))`;
|
|
3046
|
+
const ids = (helper, scope, user) => ` select a.id
|
|
3047
|
+
from ${allowKeys(scope)}
|
|
3048
|
+
cross join lateral ${helper}(${user}g.grant_key) a(id)
|
|
3049
|
+
except
|
|
3050
|
+
select d.id
|
|
3051
|
+
from ${denyKeys(scope)}
|
|
3052
|
+
cross join lateral ${helper}(${user}g.grant_key) d(id)`;
|
|
3053
|
+
const conditionedIds = (helper, scope, user) => ` select a.id
|
|
3054
|
+
from (
|
|
3055
|
+
select g.grant_key from ${allowKeys(scope)}
|
|
3056
|
+
union all
|
|
3057
|
+
select g.grant_key from ${keys}(p_permission, ${quoteLiteral(scope)}, 'conditioned-allow') g(grant_key)
|
|
3058
|
+
where p_conditioned
|
|
3059
|
+
) g
|
|
3060
|
+
cross join lateral ${helper}(${user}g.grant_key) a(id)
|
|
3061
|
+
except
|
|
3062
|
+
select d.id
|
|
3063
|
+
from (
|
|
3064
|
+
select g.grant_key from ${denyKeys(scope)}
|
|
3065
|
+
except
|
|
3066
|
+
select g.grant_key from ${keys}(p_permission, ${quoteLiteral(scope)}, 'conditioned-deny') g(grant_key)
|
|
3067
|
+
where p_conditioned
|
|
3068
|
+
) g
|
|
3069
|
+
cross join lateral ${helper}(${user}g.grant_key) d(id)`;
|
|
3070
|
+
const keysBody = (scope, bodies, filtered) => {
|
|
3071
|
+
const rows = ["global", scope].flatMap((at) => Object.entries(grants.get(at) ?? {}).toSorted(byKey).flatMap(([key, effects]) => ["allow", "deny"].flatMap((effect) => effects[effect].map((grant) => `(${[
|
|
3072
|
+
key,
|
|
3073
|
+
at,
|
|
3074
|
+
effect,
|
|
3075
|
+
grant
|
|
3076
|
+
].map(quoteLiteral).join(", ")})`))));
|
|
3077
|
+
if (new Set(["global", scope].flatMap((at) => Object.entries(grants.get(at) ?? {}).flatMap(([key, effects]) => effects.allow.length > 0 ? [key] : []))).size === 0) return {
|
|
3078
|
+
sql: " select null::text where false",
|
|
3079
|
+
vars: []
|
|
3080
|
+
};
|
|
3081
|
+
const hasBody = bodies.has;
|
|
3082
|
+
const idsBody = bodies.ids(scope);
|
|
3083
|
+
return {
|
|
3084
|
+
sql: ` with pdk_m(key, scope, effect, grant_key) as (
|
|
3085
|
+
values
|
|
3086
|
+
${rows.join(",\n ")}
|
|
3087
|
+
),
|
|
3088
|
+
pdk_w as (
|
|
3089
|
+
select pdk_m.key, pdk_m.scope, pdk_m.effect, pdk_m.grant_key
|
|
3090
|
+
from pdk_m${filtered ? `\n where pdk_m.key in (select ${Object.keys(renamed).length === 0 ? "k.key" : `coalesce(${quoteLiteral(JSON.stringify(renamed))}::jsonb ->> k.key, k.key)`} from pg_catalog.unnest(p_keys) k(key))` : ""}
|
|
3091
|
+
),
|
|
3092
|
+
pdk_g as (
|
|
3093
|
+
${hasBody.sql}
|
|
3094
|
+
),
|
|
3095
|
+
pdk_s as (
|
|
3096
|
+
select pdk_i.grant_key
|
|
3097
|
+
from (
|
|
3098
|
+
${idsBody.sql}
|
|
3099
|
+
) pdk_i(id, grant_key)
|
|
3100
|
+
where pdk_i.id = p_id
|
|
3101
|
+
),
|
|
3102
|
+
pdk_h as (
|
|
3103
|
+
select pdk_w.key, pdk_w.scope, pdk_w.effect
|
|
3104
|
+
from pdk_w
|
|
3105
|
+
where (pdk_w.scope = 'global' and pdk_w.grant_key in (select pdk_g.grant_key from pdk_g))
|
|
3106
|
+
or (pdk_w.scope = ${quoteLiteral(scope)} and pdk_w.grant_key in (select pdk_s.grant_key from pdk_s))
|
|
3107
|
+
)
|
|
3108
|
+
select pdk_k.key
|
|
3109
|
+
from (select distinct pdk_w.key from pdk_w where pdk_w.effect = 'allow') pdk_k
|
|
3110
|
+
where (exists (${heldSql("global", "allow")}) and not exists (${heldSql("global", "deny")}))
|
|
3111
|
+
or (exists (${heldSql(scope, "allow")}) and not exists (${heldSql(scope, "deny")}))
|
|
3112
|
+
order by 1`,
|
|
3113
|
+
vars: [.../* @__PURE__ */ new Set([...hasBody.vars, ...idsBody.vars])]
|
|
3114
|
+
};
|
|
3115
|
+
};
|
|
3116
|
+
const chunks = [grantsFunction(ctx, grants, renamed, anonExecute), `-- the helpers by permission key: unconditional allows minus any deny
|
|
3117
|
+
${definer(qualified(ctx, PERMISSION_HELPERS.has), "p_permission text", "boolean", has(qualified(ctx, HELPERS.has), ""))}
|
|
3118
|
+
${grantsSql(qualified(ctx, PERMISSION_HELPERS.has), "text", anonExecute)}`];
|
|
3119
|
+
for (const scope of ctx.scopes) {
|
|
3120
|
+
const fn = qualified(ctx, checkName(permittedByPermissionHelper(scope.name)));
|
|
3121
|
+
chunks.push(`${definer(fn, "p_permission text", `setof ${scopeTypeOf(ctx, scope.name)}`, ids(qualified(ctx, permittedIdsHelper(scope.name)), scope.name, ""))}
|
|
3122
|
+
${grantsSql(fn, "text", anonExecute)}`);
|
|
3123
|
+
const keysFn = qualified(ctx, checkName(permissionKeysHelper(scope.name)));
|
|
3124
|
+
const type = scopeTypeOf(ctx, scope.name);
|
|
3125
|
+
const caller = grantBodies({
|
|
3126
|
+
...ctx,
|
|
3127
|
+
grantSet: true
|
|
3128
|
+
});
|
|
3129
|
+
chunks.push(`-- the permission keys the caller holds on one ${scope.name}: what permdock_has_permission or permitted_${scope.name}_ids_by_permission answers for each key, in one call
|
|
3130
|
+
${keysFunction(keysFn, `p_id ${type}`, keysBody(scope.name, caller, false), grantsSql(keysFn, type, anonExecute), parallel)}
|
|
3131
|
+
${keysFunction(keysFn, `p_id ${type}, p_keys text[]`, keysBody(scope.name, caller, true), grantsSql(keysFn, `${type}, text[]`, anonExecute), parallel)}`);
|
|
3132
|
+
chunks.push(`-- with p_conditioned true, also the instances a conditioned allow reaches, minus only unconditional denies: the caller applies the row condition
|
|
3133
|
+
${definer(fn, "p_permission text, p_conditioned boolean", `setof ${scopeTypeOf(ctx, scope.name)}`, conditionedIds(qualified(ctx, permittedIdsHelper(scope.name)), scope.name, ""))}
|
|
3134
|
+
${grantsSql(fn, "text, boolean", anonExecute)}`);
|
|
3135
|
+
}
|
|
3136
|
+
if (ctx.authorize !== "database") return `${chunks.join("\n\n")}\n`;
|
|
3137
|
+
const user = ctx.dialect === "supabase" ? "uuid" : "text";
|
|
3138
|
+
const revoke = (fn) => `revoke execute on function ${fn}(${user}, text) from public, anon, authenticated;`;
|
|
3139
|
+
const hasFor = qualified(ctx, PERMISSION_HELPERS.hasFor);
|
|
3140
|
+
chunks.push(`-- the same for a user the caller names; no client role may execute them
|
|
3141
|
+
${definer(hasFor, `p_user ${user}, p_permission text`, "boolean", has(qualified(ctx, HELPERS.hasFor), "p_user, "))}
|
|
3142
|
+
${revoke(hasFor)}`);
|
|
3143
|
+
for (const scope of ctx.scopes) {
|
|
3144
|
+
const fn = qualified(ctx, checkName(`${permittedByPermissionHelper(scope.name)}_for`));
|
|
3145
|
+
chunks.push(`${definer(fn, `p_user ${user}, p_permission text`, `setof ${scopeTypeOf(ctx, scope.name)}`, ids(qualified(ctx, permittedForHelper(scope.name)), scope.name, "p_user, "))}
|
|
3146
|
+
${revoke(fn)}`);
|
|
3147
|
+
chunks.push(`${definer(fn, `p_user ${user}, p_permission text, p_conditioned boolean`, `setof ${scopeTypeOf(ctx, scope.name)}`, conditionedIds(qualified(ctx, permittedForHelper(scope.name)), scope.name, "p_user, "))}
|
|
3148
|
+
revoke execute on function ${fn}(${user}, text, boolean) from public, anon, authenticated;`);
|
|
3149
|
+
const keysFor = qualified(ctx, checkName(permissionKeysForHelper(scope.name)));
|
|
3150
|
+
const type = scopeTypeOf(ctx, scope.name);
|
|
3151
|
+
const named = grantBodies({
|
|
3152
|
+
...forUserContext(ctx),
|
|
3153
|
+
grantSet: true
|
|
3154
|
+
});
|
|
3155
|
+
chunks.push(`${keysFunction(keysFor, `p_user ${user}, p_id ${type}`, keysBody(scope.name, named, false), `revoke execute on function ${keysFor}(${user}, ${type}) from public, anon, authenticated;`, parallel)}
|
|
3156
|
+
${keysFunction(keysFor, `p_user ${user}, p_id ${type}, p_keys text[]`, keysBody(scope.name, named, true), `revoke execute on function ${keysFor}(${user}, ${type}, text[]) from public, anon, authenticated;`, parallel)}`);
|
|
3157
|
+
}
|
|
3158
|
+
return `${chunks.join("\n\n")}\n`;
|
|
3159
|
+
}
|
|
3160
|
+
// src/cli/sql/tables.ts
|
|
3161
|
+
/**
|
|
3162
|
+
* The `schema.table` an `rls.tables` entry names, or `resource` when it names
|
|
3163
|
+
* none or is `false`.
|
|
3164
|
+
*/
|
|
3165
|
+
function tableNameOf(entry, resource, tables) {
|
|
3166
|
+
if (entry === void 0 || entry === false) return resource;
|
|
3167
|
+
if (typeof entry === "string") return entry;
|
|
3168
|
+
if ("tableOf" in entry) {
|
|
3169
|
+
const owner = tables?.[entry.tableOf];
|
|
3170
|
+
return typeof owner === "object" && "tableOf" in owner ? entry.tableOf : tableNameOf(owner, entry.tableOf);
|
|
3171
|
+
}
|
|
3172
|
+
return entry.table ?? resource;
|
|
3173
|
+
}
|
|
3174
|
+
/**
|
|
3175
|
+
* `rls.tables` as resource to table name, the `via` objects reduced to their
|
|
3176
|
+
* `table` and the `false` entries left out.
|
|
3177
|
+
*/
|
|
3178
|
+
function tableNames(tables) {
|
|
3179
|
+
return tables === void 0 ? void 0 : Object.fromEntries(Object.entries(tables).filter(([, entry]) => entry !== false).map(([resource, entry]) => [resource, tableNameOf(entry, resource, tables)]));
|
|
3180
|
+
}
|
|
3181
|
+
function isOwner(entry) {
|
|
3182
|
+
return typeof entry === "object" && !("tableOf" in entry);
|
|
3183
|
+
}
|
|
3184
|
+
/**
|
|
3185
|
+
* The resources `rls.tables` marks `false` or `{ tableOf }`, plus every
|
|
3186
|
+
* resource an owner's `also` names: no policies of their own, their grants only
|
|
3187
|
+
* seeded.
|
|
3188
|
+
*/
|
|
3189
|
+
function tablelessResources(tables) {
|
|
3190
|
+
const out = /* @__PURE__ */ new Set();
|
|
3191
|
+
for (const [resource, entry] of Object.entries(tables ?? {})) {
|
|
3192
|
+
if (entry === false || typeof entry === "object" && "tableOf" in entry) out.add(resource);
|
|
3193
|
+
if (isOwner(entry)) for (const name of entry.also ?? []) out.add(name);
|
|
3194
|
+
}
|
|
3195
|
+
return out;
|
|
3196
|
+
}
|
|
3197
|
+
/**
|
|
3198
|
+
* Rejects a `{ tableOf }` entry that names its own resource, a `false` entry or
|
|
3199
|
+
* another `{ tableOf }` entry: the owner must have a table of its own.
|
|
3200
|
+
*/
|
|
3201
|
+
function checkSharedTables(tables) {
|
|
3202
|
+
for (const [resource, entry] of Object.entries(tables ?? {})) {
|
|
3203
|
+
if (typeof entry === "string" || entry === false || !("tableOf" in entry)) continue;
|
|
3204
|
+
const owner = tables?.[entry.tableOf];
|
|
3205
|
+
if (entry.tableOf === resource || owner === false || typeof owner === "object" && "tableOf" in owner) throw configError(`PermDock CLI: rls.tables.${resource}.tableOf names ${entry.tableOf}, which must be another resource with a table of its own`);
|
|
3206
|
+
}
|
|
3207
|
+
}
|
|
3208
|
+
function singular(name) {
|
|
3209
|
+
if (name.endsWith("ies")) return `${name.slice(0, -3)}y`;
|
|
3210
|
+
if (name.endsWith("sses")) return name.slice(0, -2);
|
|
3211
|
+
return name.endsWith("s") && !name.endsWith("ss") ? name.slice(0, -1) : name;
|
|
3212
|
+
}
|
|
3213
|
+
/** The `via` entries of `rls.tables`, by resource. */
|
|
3214
|
+
function resolveVias(tables, scopes, dialect) {
|
|
3215
|
+
const out = {};
|
|
3216
|
+
for (const [resource, entry] of Object.entries(tables ?? {})) {
|
|
3217
|
+
if (!isOwner(entry) || entry.via === void 0) continue;
|
|
3218
|
+
const { via } = entry;
|
|
3219
|
+
const scope = via.scope ?? scopes[0]?.name;
|
|
3220
|
+
if (scope === void 0 || !scopes.some((item) => item.name === scope)) throw configError(`PermDock CLI: rls.tables.${resource}.via.scope '${scope ?? ""}' is not a scope of the policy (${scopes.map((item) => item.name).join(", ")})`);
|
|
3221
|
+
const name = singular(via.table.slice(via.table.lastIndexOf(".") + 1));
|
|
3222
|
+
out[resource] = {
|
|
3223
|
+
helper: permittedIdsHelper(name),
|
|
3224
|
+
key: via.key ?? `${name}_id`,
|
|
3225
|
+
scope,
|
|
3226
|
+
table: via.table.includes(".") ? via.table : `public.${via.table}`,
|
|
3227
|
+
column: via.column,
|
|
3228
|
+
id: via.id ?? "id",
|
|
3229
|
+
type: via.type ?? (dialect === "supabase" ? "uuid" : "text")
|
|
3230
|
+
};
|
|
3231
|
+
}
|
|
3232
|
+
const helpers = /* @__PURE__ */ new Map();
|
|
3233
|
+
for (const [resource, via] of Object.entries(out)) {
|
|
3234
|
+
const seen = helpers.get(via.helper);
|
|
3235
|
+
if (seen !== void 0 && (seen.table !== via.table || seen.column !== via.column || seen.id !== via.id || seen.scope !== via.scope || seen.type !== via.type)) throw configError(`PermDock CLI: rls.tables.${resource}.via names ${via.helper}, which another resource defines over a different parent; give the parents different table names`);
|
|
3236
|
+
helpers.set(via.helper, via);
|
|
3237
|
+
}
|
|
3238
|
+
return Object.keys(out).length === 0 ? void 0 : out;
|
|
3239
|
+
}
|
|
3240
|
+
export { tokenScopesPlan as A, hookTeamReader as B, forUserContext as C, seedSql as D, memoReadsSql as E, API_KEY_ALLOWS as F, closureBackfillSql as G, POLICY_BUNDLE_FORMAT as H, apiKeyAllowsCall as I, graphPlan as J, closureDepths as K, apiKeyFields as L, guardAuthAdminGrants as M, unguardAuthAdminGrants as N, TOKEN_SCOPE_ALLOWS as O, capabilityAccessSql as P, apiKeysPlan as R, accessSql as S, helpersSql as T, bundleLoaderSql as U, hookTeamsHelper as V, policyBundle as W, graphSql as Y, sourceTransferTriggerSql as _, tablelessResources as a, ASSIGNMENTS as b, permissionHelpersSql as c, permittedByPermissionHelper as d, requiresSql as f, sourceRowsSql as g, sourceHoldersTriggerSql as h, tableNames as i, memoReadTriggersSql as j, tokenScopeAllowsCall as k, permissionKeysForHelper as l, pairsSql as m, resolveVias as n, PERMISSION_HELPERS as o, holderSources as p, graphIdsSql as q, tableNameOf as r, checkName as s, checkSharedTables as t, permissionKeysHelper as u, holdersTriggerSql as v, grantBodies as w, OWNERSHIP as x, transferTriggerSql as y, HOOK_TEAM_READER as z };
|