permdock 0.25.1 → 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-8F9VSQrK.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-BUVqRmaJ.js +0 -36
- package/dist/arazzo-CWmM8pWw.js +0 -77
- 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-DIvUMac7.js +0 -242
- package/dist/casbin-qpG_ZphP.js +0 -30
- 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-CXgE1qpa.js +0 -86
- package/dist/codemod-BJ0Kgv9b.js +0 -36
- package/dist/codemod-DjgVx3RQ.js +0 -2800
- 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-DUHSRdoQ.js +0 -152
- package/dist/config-CgA_Z5Ts.js +0 -26
- package/dist/config-DC7aiuhP.js +0 -116
- package/dist/config-report-B31MnuKf.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-Dvt1_ROJ.js +0 -3560
- package/dist/doctor-JLouRSQt.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-D17P8vo0.js +0 -827
- package/dist/gen-YA3SK59O.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-B8zbuskR.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-BdgWNuc3.js +0 -96
- package/dist/init-DKRhYiGW.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-DEvccJwP.js +0 -68
- package/dist/login-IIUDSAYW.js +0 -257
- package/dist/lru-8q4WZjBV.js +0 -28
- package/dist/manifest-BoCYBbQL.js +0 -46
- package/dist/manifest-C6eFl3Vo.d.ts +0 -349
- package/dist/manifest-CZ-GmsOL.js +0 -401
- 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-BFUnL8Yi.js +0 -137
- package/dist/openapi-Cc-aS9xC.js +0 -416
- package/dist/openapi-DcjyfR1g.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-LDciF_4t.js +0 -96
- package/dist/output-files-BYscrQl-.js +0 -1
- package/dist/output-files-CM0BnH05.js +0 -150
- package/dist/ownership-DvK6INyx.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-B5YjtUGd.js +0 -1532
- package/dist/powersync-BgUsk2Nf.js +0 -1
- package/dist/powersync-Dx7odzyw.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-Pde1lapF.js +0 -257
- package/dist/pull-a4RpDxk8.js +0 -1
- 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-D5_kABup.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-BI687j8q.js +0 -2700
- package/dist/rls-CKLHLcRl.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-B4heHtD1.js +0 -1
- package/dist/run-BG2kPruh.js +0 -694
- 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-BvTBo9-D.js +0 -29
- package/dist/schema-BlnU_TzE.js +0 -414
- package/dist/schema-grK6TTBH.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-DzNdLezx.js +0 -51
- package/dist/skills-nPLVGtGH.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-dk1kB9bJ.js +0 -92
- package/dist/supabase-hook-Bu5gkzix.js +0 -1
- package/dist/supabase-hook-Cf9zKz8T.js +0 -4263
- package/dist/supautils-BREOPaHY.js +0 -1186
- package/dist/support-session-BGeEYDSq.js +0 -158
- package/dist/tables-DnNACfAr.js +0 -4003
- 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-BkDU1dYf.js +0 -762
- package/dist/usage-DNj42KHA.js +0 -32
- package/dist/usage-DrB_tDNk.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-Boehaks6.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
package/dist/tables-DnNACfAr.js
DELETED
|
@@ -1,4003 +0,0 @@
|
|
|
1
|
-
import { c as listPermissions, h as formerKeys } from "./permission-registry-B8tYxPIt.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-8-pCScBO.js";
|
|
3
|
-
import { o as flattenGrantee } from "./grantee-OG4klcNr.js";
|
|
4
|
-
import { c as rootScope, d as scopeList, l as scopeChain, s as resolveScope } from "./scopes-gdH__vDZ.js";
|
|
5
|
-
import { r as relationCondition, t as inheritCondition } from "./grantee-conditions-Dzprappv.js";
|
|
6
|
-
import { l as partitionsOf, p as scopeField } from "./tenancy-BlxY5T0q.js";
|
|
7
|
-
import { a as delegatedScopeMap } from "./permdock-B3zE16To.js";
|
|
8
|
-
import { i as configError } from "./errors-BhRkoNS7.js";
|
|
9
|
-
import { d as sqlTextArray, i as qualifySqlTable, t as SQL_IDENT } from "./sql-0WjxIp9g.js";
|
|
10
|
-
import { a as scopeMembershipTable, d as restrictedRowsSql, i as scopeColumn, l as relationArmSql } from "./compile-Cvru58id.js";
|
|
11
|
-
import { d as keptKeys, l as roleColumn, t as AUTHZ_VERSION_TABLE, u as roleManifest } from "./sources-C4vkzZJV.js";
|
|
12
|
-
import { A as quoteQualified, D as qualified, E as helperSchema, L as scopeTypeOf, O as quoteIdent, _ as subjectClaimJsonSql, d as keyTenantSql, f as kindFilterSql, h as roleKindSql, i as allowEntry, j as quoteTable, k as quoteLiteral, m as memberVia, n as GLOBAL_ROLES, o as rootName, r as HELPERS, s as signedIn, t as CUSTOM_ROLES, u as globalKindFilterSql, v as subjectClaimSql, w as CLI, x as userIdHelperSql, y as subjectIdSql, z as tenantTypeOf } from "./shared-DfaIWvIJ.js";
|
|
13
|
-
//#region src/cli/sql/active.ts
|
|
14
|
-
function checkActiveRow(label, row) {
|
|
15
|
-
quoteTable(row.table);
|
|
16
|
-
quoteIdent(row.id);
|
|
17
|
-
if (row.disabledAt !== void 0) quoteIdent(row.disabledAt);
|
|
18
|
-
if (row.status !== void 0) {
|
|
19
|
-
quoteIdent(row.status);
|
|
20
|
-
if (row.active === void 0 || row.active.length === 0) throw configError(`PermDock CLI: ${label}.status needs the active values in ${label}.active`);
|
|
21
|
-
}
|
|
22
|
-
if (row.disabledAt === void 0 && row.status === void 0) throw configError(`PermDock CLI: ${label} needs disabledAt or status to tell an active row`);
|
|
23
|
-
}
|
|
24
|
-
/** Validates `rls.suspension` and keys its scopes by declared name. */
|
|
25
|
-
function checkSuspension(suspension, scopes) {
|
|
26
|
-
if (suspension === void 0) return;
|
|
27
|
-
if (suspension.users !== void 0) checkActiveRow("rls.suspension.users", suspension.users);
|
|
28
|
-
const byName = {};
|
|
29
|
-
for (const [key, row] of Object.entries(suspension.scopes ?? {})) {
|
|
30
|
-
const name = resolveScope(scopes, key);
|
|
31
|
-
if (name === void 0) throw configError(`PermDock CLI: rls.suspension.scopes.${key} names a scope the policy does not declare`);
|
|
32
|
-
checkActiveRow(`rls.suspension.scopes.${key}`, row);
|
|
33
|
-
if (row.keep !== void 0 && !Array.isArray(row.keep)) throw configError(`PermDock CLI: rls.suspension.scopes.${key}.keep is a list of permissions or permission keys`);
|
|
34
|
-
const keep = keptKeys(row);
|
|
35
|
-
const { keep: _given, ...active } = row;
|
|
36
|
-
byName[name] = keep.length === 0 ? active : {
|
|
37
|
-
...active,
|
|
38
|
-
keep
|
|
39
|
-
};
|
|
40
|
-
}
|
|
41
|
-
const memberships = suspension.memberships;
|
|
42
|
-
if (memberships?.keep !== void 0 && !Array.isArray(memberships.keep)) throw configError("PermDock CLI: rls.suspension.memberships.keep is a list of permissions or permission keys");
|
|
43
|
-
const keep = keptKeys(memberships);
|
|
44
|
-
return {
|
|
45
|
-
...suspension.users === void 0 ? {} : { users: suspension.users },
|
|
46
|
-
...Object.keys(byName).length === 0 ? {} : { scopes: byName },
|
|
47
|
-
...keep.length === 0 ? {} : { memberships: { keep } }
|
|
48
|
-
};
|
|
49
|
-
}
|
|
50
|
-
function disabledKeep(ctx) {
|
|
51
|
-
return keptKeys(ctx.suspension?.memberships);
|
|
52
|
-
}
|
|
53
|
-
function activeMembershipSql(ctx, disabledAt, permission = ctx.permission === void 0 ? void 0 : { key: ctx.permission }) {
|
|
54
|
-
if (disabledAt === void 0) return [];
|
|
55
|
-
const keep = disabledKeep(ctx);
|
|
56
|
-
if (permission !== void 0 && "key" in permission && keep.includes(permission.key)) return [];
|
|
57
|
-
return permission !== void 0 && "sql" in permission && keep.length > 0 ? [`(${disabledAt} is null or ${permission.sql} = any(array[${keep.map(quoteLiteral).join(", ")}]::text[]))`] : [`${disabledAt} is null`];
|
|
58
|
-
}
|
|
59
|
-
function keptRowSql(keep, permission) {
|
|
60
|
-
const kind = `coalesce(jsonb_typeof(${keep}), 'null')`;
|
|
61
|
-
if (permission === void 0) return `${kind} = 'null'`;
|
|
62
|
-
return `case ${kind} when 'null' then true when 'array' then ${keep} @> jsonb_build_array(${"key" in permission ? quoteLiteral(permission.key) : permission.sql}) else false end`;
|
|
63
|
-
}
|
|
64
|
-
/**
|
|
65
|
-
* Whether `id` is among the active rows' ids: a missing row is suspended, so
|
|
66
|
-
* the check fails closed, and so does a null `id`. `id` stays outside the
|
|
67
|
-
* subquery so a column of the same name on `row.table` cannot capture it.
|
|
68
|
-
*/
|
|
69
|
-
function activeRowSql(row, id) {
|
|
70
|
-
const table = quoteTable(qualifySqlTable(row.table));
|
|
71
|
-
const parts = [];
|
|
72
|
-
if (row.disabledAt !== void 0) parts.push(`s.${quoteIdent(row.disabledAt)} is null`);
|
|
73
|
-
if (row.status !== void 0) {
|
|
74
|
-
const values = (row.active ?? []).map(quoteLiteral).join(", ");
|
|
75
|
-
parts.push(`s.${quoteIdent(row.status)}::text = any(array[${values}]::text[])`);
|
|
76
|
-
}
|
|
77
|
-
const where = parts.length === 0 ? "" : ` where ${parts.join(" and ")}`;
|
|
78
|
-
return `coalesce(${id} in (select s.${quoteIdent(row.id)} from ${table} s${where}), false)`;
|
|
79
|
-
}
|
|
80
|
-
function activeJoin(row, id, alias) {
|
|
81
|
-
const table = quoteTable(qualifySqlTable(row.table));
|
|
82
|
-
const parts = [`${alias}.${quoteIdent(row.id)} = ${id}`];
|
|
83
|
-
if (row.disabledAt !== void 0) parts.push(`${alias}.${quoteIdent(row.disabledAt)} is null`);
|
|
84
|
-
if (row.status !== void 0) {
|
|
85
|
-
const values = (row.active ?? []).map(quoteLiteral).join(", ");
|
|
86
|
-
parts.push(`${alias}.${quoteIdent(row.status)}::text = any(array[${values}]::text[])`);
|
|
87
|
-
}
|
|
88
|
-
return `join ${table} ${alias} on ${parts.join(" and ")}`;
|
|
89
|
-
}
|
|
90
|
-
function activeUserChecks(ctx, user, alias, indent) {
|
|
91
|
-
const row = ctx.suspension?.users;
|
|
92
|
-
return row === void 0 ? {
|
|
93
|
-
joins: [],
|
|
94
|
-
filters: []
|
|
95
|
-
} : {
|
|
96
|
-
joins: [`${indent}${activeJoin(row, user, alias)}`],
|
|
97
|
-
filters: []
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
function activeInstanceChecks(ctx, scope, idOf, aliasOf, indent, permission = ctx.permission === void 0 ? void 0 : { key: ctx.permission }) {
|
|
101
|
-
const joins = [];
|
|
102
|
-
const filters = [];
|
|
103
|
-
for (const name of scopeChain(ctx.scopes, scope)) {
|
|
104
|
-
const row = ctx.suspension?.scopes?.[name];
|
|
105
|
-
if (row === void 0) continue;
|
|
106
|
-
const id = idOf(name);
|
|
107
|
-
if (id === void 0) throw configError(`PermDock CLI: rls.suspension.scopes.${name} needs the ${name} id on ${scope} memberships: add columns.${name} to the ${scope} memberships table`);
|
|
108
|
-
const keep = keptKeys(row);
|
|
109
|
-
if (permission !== void 0 && "key" in permission && keep.includes(permission.key)) continue;
|
|
110
|
-
const cast = `(${id})::${scopeTypeOf(ctx, name)}`;
|
|
111
|
-
if (keep.length === 0) {
|
|
112
|
-
joins.push(`${indent}${activeJoin(row, cast, aliasOf(name))}`);
|
|
113
|
-
continue;
|
|
114
|
-
}
|
|
115
|
-
const active = activeRowSql(row, cast);
|
|
116
|
-
filters.push(permission !== void 0 && "sql" in permission ? `(${active} or ${permission.sql} = any(array[${keep.map(quoteLiteral).join(", ")}]::text[]))` : active);
|
|
117
|
-
}
|
|
118
|
-
return {
|
|
119
|
-
joins,
|
|
120
|
-
filters
|
|
121
|
-
};
|
|
122
|
-
}
|
|
123
|
-
/** The active-user check for `user`; empty without `rls.suspension.users`. */
|
|
124
|
-
function activeUserSql(ctx, user = subjectIdSql(ctx)) {
|
|
125
|
-
const row = ctx.suspension?.users;
|
|
126
|
-
return row === void 0 ? [] : [activeRowSql(row, user)];
|
|
127
|
-
}
|
|
128
|
-
/**
|
|
129
|
-
* The permission of a grant key held in `grant`: `key#group` and `key@level`
|
|
130
|
-
* name `key`.
|
|
131
|
-
*/
|
|
132
|
-
function grantPermissionSql(grant) {
|
|
133
|
-
return { sql: `split_part(split_part(${grant}, '#', 1), '@', 1)` };
|
|
134
|
-
}
|
|
135
|
-
/**
|
|
136
|
-
* The active-instance check for every suspendable scope on `scope`'s chain: its
|
|
137
|
-
* own and each ancestor's. `idOf` gives the SQL for the id the membership holds
|
|
138
|
-
* for a scope on that chain. A scope's `keep` lets `permission` through a
|
|
139
|
-
* suspended instance: a kept key known now drops its check, and one read at run
|
|
140
|
-
* time is compared with the kept keys.
|
|
141
|
-
*/
|
|
142
|
-
function activeInstancesSql(ctx, scope, idOf, permission = ctx.permission === void 0 ? void 0 : { key: ctx.permission }) {
|
|
143
|
-
const parts = [];
|
|
144
|
-
for (const name of scopeChain(ctx.scopes, scope)) {
|
|
145
|
-
const row = ctx.suspension?.scopes?.[name];
|
|
146
|
-
if (row === void 0) continue;
|
|
147
|
-
const id = idOf(name);
|
|
148
|
-
if (id === void 0) throw configError(`PermDock CLI: rls.suspension.scopes.${name} needs the ${name} id on ${scope} memberships: add columns.${name} to the ${scope} memberships table`);
|
|
149
|
-
const keep = keptKeys(row);
|
|
150
|
-
if (permission !== void 0 && "key" in permission && keep.includes(permission.key)) continue;
|
|
151
|
-
const active = activeRowSql(row, `(${id})::${scopeTypeOf(ctx, name)}`);
|
|
152
|
-
parts.push(permission !== void 0 && "sql" in permission && keep.length > 0 ? `(${active} or ${permission.sql} = any(array[${keep.map(quoteLiteral).join(", ")}]::text[]))` : active);
|
|
153
|
-
}
|
|
154
|
-
return parts;
|
|
155
|
-
}
|
|
156
|
-
//#endregion
|
|
157
|
-
//#region src/cli/sql/names.ts
|
|
158
|
-
/** The closure table graph grants read. Part of the SQL contract. */
|
|
159
|
-
const CLOSURE = { table: "permdock_closure" };
|
|
160
|
-
/**
|
|
161
|
-
* The snake_case SQL name of a resource or link (`chatThread` becomes
|
|
162
|
-
* `chat_thread`), or `undefined` when it is not made of ASCII letters, digits
|
|
163
|
-
* and underscores starting with a letter.
|
|
164
|
-
*/
|
|
165
|
-
function graphSqlName(name) {
|
|
166
|
-
if (!/^[A-Za-z][A-Za-z0-9_]*$/u.test(name)) return;
|
|
167
|
-
return name.replaceAll(/([a-z0-9])([A-Z])/gu, "$1_$2").replaceAll(/([A-Z]+)([A-Z][a-z])/gu, "$1_$2").toLowerCase();
|
|
168
|
-
}
|
|
169
|
-
function sqlNameOf(name, label) {
|
|
170
|
-
const sql = graphSqlName(name);
|
|
171
|
-
if (sql === void 0) throw configError(`PermDock CLI: ${label} is not a SQL name (letters, digits and underscores, starting with a letter), so rls generate cannot name its helper`);
|
|
172
|
-
return sql;
|
|
173
|
-
}
|
|
174
|
-
/**
|
|
175
|
-
* The helper returning the ids of `resource` the subject holds a relation on:
|
|
176
|
-
* `permitted_<snake_case resource>_ids`.
|
|
177
|
-
*/
|
|
178
|
-
function graphHelper(resource) {
|
|
179
|
-
return permittedIdsHelper(sqlNameOf(resource, `resource '${resource}'`));
|
|
180
|
-
}
|
|
181
|
-
function inheritedRowsHelper(resource) {
|
|
182
|
-
return `permitted_${sqlNameOf(resource, `resource '${resource}'`)}_rows`;
|
|
183
|
-
}
|
|
184
|
-
/**
|
|
185
|
-
* The helper returning the ids of `resource` whose `link` points into the ids
|
|
186
|
-
* it is given.
|
|
187
|
-
*/
|
|
188
|
-
function linkHelper(resource, link) {
|
|
189
|
-
return `permdock_link_${sqlNameOf(resource, `resource '${resource}'`)}_${sqlNameOf(link, `link '${link}' on ${resource}`)}`;
|
|
190
|
-
}
|
|
191
|
-
function restrictedHelper(resource) {
|
|
192
|
-
return `permdock_restricted_${sqlNameOf(resource, `resource '${resource}'`)}`;
|
|
193
|
-
}
|
|
194
|
-
/**
|
|
195
|
-
* Graph SQL parts as RLS text: values inline as literals, the subject from the
|
|
196
|
-
* dialect's claim.
|
|
197
|
-
*/
|
|
198
|
-
function graphSqlText(parts, ctx) {
|
|
199
|
-
return parts.map((part) => {
|
|
200
|
-
if ("text" in part) return part.text;
|
|
201
|
-
if ("column" in part) return quoteIdent(part.column);
|
|
202
|
-
if ("subject" in part) return subjectIdSql(ctx);
|
|
203
|
-
return typeof part.value === "string" ? quoteLiteral(part.value) : String(part.value);
|
|
204
|
-
}).join("");
|
|
205
|
-
}
|
|
206
|
-
/**
|
|
207
|
-
* The role column of an `rls.memberships` table aliased `alias`; a `through`
|
|
208
|
-
* column joins its roles table as `<alias>k`, after a newline and `indent`
|
|
209
|
-
* (inline without one).
|
|
210
|
-
*/
|
|
211
|
-
function memberRoleOf(table, alias = "m", indent) {
|
|
212
|
-
return roleColumn(table.role, qualifySqlTable(table.table), alias, {
|
|
213
|
-
label: `rls.memberships ${table.table} role`,
|
|
214
|
-
prefix: CLI,
|
|
215
|
-
...indent === void 0 ? {} : { indent }
|
|
216
|
-
});
|
|
217
|
-
}
|
|
218
|
-
/** The schema-qualified name of a table under `search_path = ''`. */
|
|
219
|
-
/** The helper returning the ids of scope `name` a grant key reaches. */
|
|
220
|
-
function permittedIdsHelper(name) {
|
|
221
|
-
if (!/^[a-z][a-z0-9_]*$/u.test(name)) throw configError(`PermDock CLI: unsafe scope name '${name}'`);
|
|
222
|
-
return `permitted_${name}_ids`;
|
|
223
|
-
}
|
|
224
|
-
/**
|
|
225
|
-
* `permitted_<scope>_ids_for(p_user, p_grant)`: the same ids for a user the
|
|
226
|
-
* caller names.
|
|
227
|
-
*/
|
|
228
|
-
function permittedForHelper(name) {
|
|
229
|
-
return `${permittedIdsHelper(name)}_for`;
|
|
230
|
-
}
|
|
231
|
-
/**
|
|
232
|
-
* The helper returning the ids of scope `name` the subject holds any live
|
|
233
|
-
* membership of.
|
|
234
|
-
*/
|
|
235
|
-
function memberIdsHelper(name) {
|
|
236
|
-
if (!/^[a-z][a-z0-9_]*$/u.test(name)) throw configError(`PermDock CLI: unsafe scope name '${name}'`);
|
|
237
|
-
return `member_${name}_ids`;
|
|
238
|
-
}
|
|
239
|
-
/**
|
|
240
|
-
* `member_<scope>_ids_for(p_user uuid)`: the same rows for a user the caller
|
|
241
|
-
* names; the token hook's helper.
|
|
242
|
-
*/
|
|
243
|
-
function memberForHelper(name) {
|
|
244
|
-
return `${memberIdsHelper(name)}_for`;
|
|
245
|
-
}
|
|
246
|
-
/**
|
|
247
|
-
* `member_<scope>_ids_of(p_user uuid)`: `member_<scope>_ids_for(p_user)` when
|
|
248
|
-
* `p_user` is the caller and no rows otherwise, so `authenticated` may execute
|
|
249
|
-
* it; better-supabase's `teamIdsOf` template calls it.
|
|
250
|
-
*/
|
|
251
|
-
function memberOfHelper(name) {
|
|
252
|
-
return `${memberIdsHelper(name)}_of`;
|
|
253
|
-
}
|
|
254
|
-
/** A scope better-supabase reads as its teams: `team` or `teams` (doctor BS417). */
|
|
255
|
-
function isTeamScope(name) {
|
|
256
|
-
return /^teams?$/u.test(name);
|
|
257
|
-
}
|
|
258
|
-
/**
|
|
259
|
-
* Whether `member_<scope>_ids_of` is generated: a team scope with
|
|
260
|
-
* `member_<scope>_ids_for`.
|
|
261
|
-
*/
|
|
262
|
-
function hasMemberOf(input, name) {
|
|
263
|
-
return isTeamScope(name) && hasMemberFor(input, name);
|
|
264
|
-
}
|
|
265
|
-
/**
|
|
266
|
-
* Whether `member_<scope>_ids_for` is generated for `name`: Supabase only (its
|
|
267
|
-
* one caller is `supabase_auth_admin`), and only where `memberships` maps a
|
|
268
|
-
* table for the scope or a membership source can hold it.
|
|
269
|
-
*/
|
|
270
|
-
function hasMemberFor(input, name) {
|
|
271
|
-
if (input.dialect !== "supabase") return false;
|
|
272
|
-
return memberForTable(input, name) !== void 0 || memberForSources(input, name).length > 0;
|
|
273
|
-
}
|
|
274
|
-
/**
|
|
275
|
-
* Whether `permitted_<scope>_users` can list the members of one instance of
|
|
276
|
-
* `name`: a mapped membership table, or sources that all read a table.
|
|
277
|
-
*/
|
|
278
|
-
function hasPermittedUsers(input, name) {
|
|
279
|
-
if (memberForTable(input, name) !== void 0) return true;
|
|
280
|
-
const sources = memberForSources(input, name);
|
|
281
|
-
return sources.length > 0 && sources.every((source) => source.sql.holders !== void 0);
|
|
282
|
-
}
|
|
283
|
-
/**
|
|
284
|
-
* The table `member_<scope>_ids_for` reads for scope `name`, when `memberships`
|
|
285
|
-
* maps one with its id column.
|
|
286
|
-
*/
|
|
287
|
-
function memberForTable(input, name) {
|
|
288
|
-
const table = scopeMembershipTable(input.memberships, input.scopes, name);
|
|
289
|
-
return table !== void 0 && scopeColumn(table, input.scopes, name) !== void 0 ? table : void 0;
|
|
290
|
-
}
|
|
291
|
-
/**
|
|
292
|
-
* The sources `member_<scope>_ids_for` reads: none when a table is mapped, as
|
|
293
|
-
* in `database` mode.
|
|
294
|
-
*/
|
|
295
|
-
function memberForSources(input, name) {
|
|
296
|
-
if (memberForTable(input, name) !== void 0) return [];
|
|
297
|
-
return (input.memberSources ?? []).filter((source) => source.sql.scope === void 0 || source.sql.scope === name);
|
|
298
|
-
}
|
|
299
|
-
/**
|
|
300
|
-
* The membership sources that can hold scope `name` when `memberships` maps no
|
|
301
|
-
* table for it: every `tableMembershipSource` source and the
|
|
302
|
-
* `junctionMembershipSource` sources of that scope. Empty outside `database`
|
|
303
|
-
* mode.
|
|
304
|
-
*/
|
|
305
|
-
function scopeSources(ctx, name) {
|
|
306
|
-
if (ctx.authorize !== "database" || scopeTable(ctx, name) !== void 0) return [];
|
|
307
|
-
return (ctx.sources ?? []).filter((source) => source.sql.scope === void 0 || source.sql.scope === name);
|
|
308
|
-
}
|
|
309
|
-
/**
|
|
310
|
-
* The membership table mapped for scope `name`, with the column of its id and
|
|
311
|
-
* of the first scope's id.
|
|
312
|
-
*/
|
|
313
|
-
function scopeTable(ctx, name) {
|
|
314
|
-
const table = scopeMembershipTable(ctx.memberships, ctx.scopes, name);
|
|
315
|
-
if (table === void 0) return;
|
|
316
|
-
const column = scopeColumn(table, ctx.scopes, name);
|
|
317
|
-
if (column === void 0) return;
|
|
318
|
-
const root = rootScope(ctx.scopes);
|
|
319
|
-
const tenantColumn = root !== void 0 && scopeChain(ctx.scopes, name).includes(root) ? scopeColumn(table, ctx.scopes, root) : void 0;
|
|
320
|
-
return tenantColumn === void 0 ? {
|
|
321
|
-
table,
|
|
322
|
-
column
|
|
323
|
-
} : {
|
|
324
|
-
table,
|
|
325
|
-
column,
|
|
326
|
-
tenantColumn
|
|
327
|
-
};
|
|
328
|
-
}
|
|
329
|
-
//#endregion
|
|
330
|
-
//#region src/cli/rls/api-keys.ts
|
|
331
|
-
const API_KEY_ALLOWS = "permdock_api_key_allows";
|
|
332
|
-
const DEFAULTS = {
|
|
333
|
-
claim: "api_key",
|
|
334
|
-
scopes: "scopes",
|
|
335
|
-
tenant: "tenant",
|
|
336
|
-
roles: "roles"
|
|
337
|
-
};
|
|
338
|
-
function field(settings, name) {
|
|
339
|
-
const value = settings[name] ?? DEFAULTS[name];
|
|
340
|
-
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}`);
|
|
341
|
-
return value;
|
|
342
|
-
}
|
|
343
|
-
function apiKeyFields(setting) {
|
|
344
|
-
const settings = setting === true ? {} : setting;
|
|
345
|
-
return {
|
|
346
|
-
claim: field(settings, "claim"),
|
|
347
|
-
scopes: field(settings, "scopes"),
|
|
348
|
-
tenant: field(settings, "tenant"),
|
|
349
|
-
roles: field(settings, "roles"),
|
|
350
|
-
serviceRoles: [...new Set(settings.serviceRoles ?? [])]
|
|
351
|
-
};
|
|
352
|
-
}
|
|
353
|
-
function apiKeysPlan(setting, declared, renamed) {
|
|
354
|
-
if (setting === void 0) return;
|
|
355
|
-
const fields = apiKeyFields(setting);
|
|
356
|
-
const unknown = fields.serviceRoles.filter((role) => !declared.has(role));
|
|
357
|
-
if (unknown.length > 0) throw configError(`PermDock CLI: rls.apiKeys.serviceRoles names roles the policy does not declare: ${unknown.join(", ")}`);
|
|
358
|
-
return {
|
|
359
|
-
...fields,
|
|
360
|
-
...Object.keys(renamed).length === 0 ? {} : { renamed }
|
|
361
|
-
};
|
|
362
|
-
}
|
|
363
|
-
function keyOf(ctx, plan) {
|
|
364
|
-
return `(select ${subjectClaimJsonSql(ctx, plan.claim)} as k) api_key`;
|
|
365
|
-
}
|
|
366
|
-
function permissionOf(plan, expr) {
|
|
367
|
-
return plan.renamed === void 0 ? expr : `coalesce(${quoteLiteral(JSON.stringify(plan.renamed))}::jsonb ->> ${expr}, ${expr})`;
|
|
368
|
-
}
|
|
369
|
-
function apiKeyAllowsCall(ctx, grant) {
|
|
370
|
-
return `${qualified(ctx, API_KEY_ALLOWS)}(${grant})`;
|
|
371
|
-
}
|
|
372
|
-
function apiKeyAllowsSql(ctx, plan, anonExecute) {
|
|
373
|
-
const fn = qualified(ctx, API_KEY_ALLOWS);
|
|
374
|
-
const scopes = `k -> ${quoteLiteral(plan.scopes)}`;
|
|
375
|
-
const grants = anonExecute ? `revoke execute on function ${fn}(text) from public;
|
|
376
|
-
grant execute on function ${fn}(text) to anon, authenticated;` : `revoke execute on function ${fn}(text) from public, anon;
|
|
377
|
-
grant execute on function ${fn}(text) to authenticated;`;
|
|
378
|
-
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
|
|
379
|
-
create or replace function ${fn}(p_grant text)
|
|
380
|
-
returns boolean
|
|
381
|
-
language sql
|
|
382
|
-
stable
|
|
383
|
-
security definer
|
|
384
|
-
set search_path = ''
|
|
385
|
-
as $$
|
|
386
|
-
select case
|
|
387
|
-
when k is null or k = 'null'::jsonb then true
|
|
388
|
-
when exists (
|
|
389
|
-
select 1 from ${qualified(ctx, "role_permissions")} rp
|
|
390
|
-
where rp.grant_key = p_grant and rp.effect = 'deny'
|
|
391
|
-
) then true
|
|
392
|
-
when jsonb_typeof(k) is distinct from 'object' or jsonb_typeof(${scopes}) is distinct from 'array' then false
|
|
393
|
-
else exists (
|
|
394
|
-
select 1
|
|
395
|
-
from jsonb_array_elements_text(${scopes}) s(permission)
|
|
396
|
-
where ${permissionOf(plan, "s.permission")} = split_part(split_part(p_grant, '#', 1), '@', 1)
|
|
397
|
-
)
|
|
398
|
-
end
|
|
399
|
-
from ${keyOf(ctx, plan)}
|
|
400
|
-
$$;
|
|
401
|
-
${grants}`;
|
|
402
|
-
}
|
|
403
|
-
function serviceRolesJson(plan) {
|
|
404
|
-
return `${quoteLiteral(JSON.stringify(plan.serviceRoles))}::jsonb`;
|
|
405
|
-
}
|
|
406
|
-
function serviceKeyRows(ctx, plan) {
|
|
407
|
-
const roles = `k -> ${quoteLiteral(plan.roles)}`;
|
|
408
|
-
return ` from ${keyOf(ctx, plan)}
|
|
409
|
-
cross join lateral jsonb_array_elements_text(
|
|
410
|
-
case jsonb_typeof(${roles}) when 'array' then ${roles} else ${serviceRolesJson(plan)} end
|
|
411
|
-
) r(role)`;
|
|
412
|
-
}
|
|
413
|
-
function serviceKeyFilters(ctx, plan, root, permission) {
|
|
414
|
-
const tenant = `k ->> ${quoteLiteral(plan.tenant)}`;
|
|
415
|
-
return [
|
|
416
|
-
`jsonb_typeof(k) = 'object'`,
|
|
417
|
-
`coalesce(${subjectIdSql(ctx)}::text, '') = ''`,
|
|
418
|
-
`coalesce(${tenant}, '') <> ''`,
|
|
419
|
-
...activeInstancesSql(ctx, root, (name) => name === root ? tenant : void 0, permission)
|
|
420
|
-
];
|
|
421
|
-
}
|
|
422
|
-
function serviceKeyIdsSql(ctx, plan, root, type) {
|
|
423
|
-
const kind = kindFilterSql(ctx, "r.role", { value: "credential" });
|
|
424
|
-
const set = ctx.grantSet === true;
|
|
425
|
-
const filters = [
|
|
426
|
-
...serviceKeyFilters(ctx, plan, root, grantPermissionSql(set ? "rp.grant_key" : "p_grant")),
|
|
427
|
-
...set ? [] : ["rp.grant_key = p_grant"],
|
|
428
|
-
`rp.scope = ${quoteLiteral(root)}`,
|
|
429
|
-
...kind === void 0 ? [] : [kind]
|
|
430
|
-
];
|
|
431
|
-
return ` select (k ->> ${quoteLiteral(plan.tenant)})::${type}${set ? ", rp.grant_key" : ""}
|
|
432
|
-
${serviceKeyRows(ctx, plan)}
|
|
433
|
-
join ${qualified(ctx, "role_permissions")} rp on rp.role = r.role
|
|
434
|
-
where ${filters.join("\n and ")}`;
|
|
435
|
-
}
|
|
436
|
-
function serviceKeyMemberSql(ctx, plan, root, type) {
|
|
437
|
-
return ` select distinct (k ->> ${quoteLiteral(plan.tenant)})::${type}
|
|
438
|
-
${serviceKeyRows(ctx, plan)}
|
|
439
|
-
where ${serviceKeyFilters(ctx, plan, root).join("\n and ")}`;
|
|
440
|
-
}
|
|
441
|
-
function ceilingIdsSql(body, allows) {
|
|
442
|
-
return ` select ids.id
|
|
443
|
-
from (
|
|
444
|
-
${body}
|
|
445
|
-
) ids(id)
|
|
446
|
-
where ${allows}`;
|
|
447
|
-
}
|
|
448
|
-
function ceilingHasSql(body, allows) {
|
|
449
|
-
return ` select ${allows} and coalesce((
|
|
450
|
-
${body}
|
|
451
|
-
), false)`;
|
|
452
|
-
}
|
|
453
|
-
//#endregion
|
|
454
|
-
//#region src/cli/shared/compare.ts
|
|
455
|
-
/**
|
|
456
|
-
* UTF-16 code-unit order, never `localeCompare`: generated SQL must match byte
|
|
457
|
-
* for byte on every machine.
|
|
458
|
-
*/
|
|
459
|
-
function byCodeUnit(a, b) {
|
|
460
|
-
return a < b ? -1 : a > b ? 1 : 0;
|
|
461
|
-
}
|
|
462
|
-
function byKey([a], [b]) {
|
|
463
|
-
return byCodeUnit(a, b);
|
|
464
|
-
}
|
|
465
|
-
//#endregion
|
|
466
|
-
//#region src/cli/rls/custom-roles.ts
|
|
467
|
-
/** The readers every helpers file ends with. Names are part of the SQL contract. */
|
|
468
|
-
const READERS = {
|
|
469
|
-
keys: "permdock_permission_keys",
|
|
470
|
-
roles: "permdock_role_permissions",
|
|
471
|
-
trusted: "permdock_trusted_role_permissions"
|
|
472
|
-
};
|
|
473
|
-
/**
|
|
474
|
-
* The custom-role objects: the tables (`database` mode), the ceiling view over
|
|
475
|
-
* the `assignable` declared roles, and `permdock_custom_keys`, which resolves
|
|
476
|
-
* one custom role to the grant keys it holds in a scope. A row in the tables
|
|
477
|
-
* can never reach a key outside the view.
|
|
478
|
-
*/
|
|
479
|
-
function customRolesSql(ctx) {
|
|
480
|
-
const custom = ctx.customRoles;
|
|
481
|
-
if (custom === void 0) return "";
|
|
482
|
-
const rp = qualified(ctx, "role_permissions");
|
|
483
|
-
const ceiling = qualified(ctx, CUSTOM_ROLES.ceiling);
|
|
484
|
-
const keys = qualified(ctx, CUSTOM_ROLES.keys);
|
|
485
|
-
const chunks = [];
|
|
486
|
-
if (ctx.authorize === "database") {
|
|
487
|
-
const tenantType = tenantTypeOf(ctx);
|
|
488
|
-
for (const [name, column, check] of [[
|
|
489
|
-
CUSTOM_ROLES.permissions,
|
|
490
|
-
"permission",
|
|
491
|
-
`,
|
|
492
|
-
effect text not null default 'allow' check (effect in ('allow', 'deny'))`
|
|
493
|
-
], [
|
|
494
|
-
CUSTOM_ROLES.includes,
|
|
495
|
-
"include_role",
|
|
496
|
-
""
|
|
497
|
-
]]) {
|
|
498
|
-
const table = qualified(ctx, name);
|
|
499
|
-
const leveled = custom.levels === true && name === CUSTOM_ROLES.permissions;
|
|
500
|
-
const unique = `${column}${name === CUSTOM_ROLES.permissions ? ", effect" : ""}${leveled ? ", coalesce(level, '')" : ""}`;
|
|
501
|
-
const index = leveled ? `drop index if exists ${qualified(ctx, quoteIdent(`${name}_key`))};
|
|
502
|
-
alter table ${table} add column if not exists level text check (level ~ '^[a-z][a-z0-9_]*$');
|
|
503
|
-
create unique index if not exists ${quoteIdent(`${name}_level_key`)}` : `create unique index if not exists ${quoteIdent(`${name}_key`)}`;
|
|
504
|
-
chunks.push(`create table if not exists ${table} (
|
|
505
|
-
tenant_id ${tenantType},
|
|
506
|
-
scope text not null default ${quoteLiteral(rootName(ctx))},
|
|
507
|
-
scope_id text,
|
|
508
|
-
role text not null,
|
|
509
|
-
${column} text not null${check}
|
|
510
|
-
);
|
|
511
|
-
-- global: no tenant or instance; a tenant role: a tenant; a shared role: no tenant or instance
|
|
512
|
-
alter table ${table} drop constraint if exists ${quoteIdent(`${name}_check`)};
|
|
513
|
-
alter table ${table} drop constraint if exists ${quoteIdent(`${name}_shape`)};
|
|
514
|
-
alter table ${table} add constraint ${quoteIdent(`${name}_shape`)} check (
|
|
515
|
-
case when scope = 'global' then tenant_id is null and scope_id is null
|
|
516
|
-
else tenant_id is not null or scope_id is null end
|
|
517
|
-
);
|
|
518
|
-
${index}
|
|
519
|
-
on ${table} (coalesce(tenant_id::text, ''), scope, coalesce(scope_id, ''), role, ${unique});
|
|
520
|
-
-- a row identity for triggers the application adds, such as an audit trigger that reads the primary key
|
|
521
|
-
alter table ${table} add column if not exists id bigint generated always as identity primary key;
|
|
522
|
-
alter table ${table} enable row level security;
|
|
523
|
-
revoke all on table ${table} from anon, authenticated, public;`);
|
|
524
|
-
}
|
|
525
|
-
}
|
|
526
|
-
chunks.push(`-- the ceiling: keys of assignable declared roles, and the denies of those roles on the same permissions
|
|
527
|
-
create or replace view ${ceiling} with (security_invoker = true) as
|
|
528
|
-
select rp.scope, rp.role, rp.permission, rp.grant_key, rp.effect
|
|
529
|
-
from ${rp} rp
|
|
530
|
-
where rp.role = any(${sqlTextArray(custom.assignable)})
|
|
531
|
-
and exists (
|
|
532
|
-
select 1 from ${rp} a
|
|
533
|
-
where a.role = rp.role
|
|
534
|
-
and a.permission = rp.permission
|
|
535
|
-
and a.scope = rp.scope
|
|
536
|
-
and a.effect = 'allow'
|
|
537
|
-
);
|
|
538
|
-
revoke all on table ${ceiling} from anon, authenticated, public;`);
|
|
539
|
-
const renames = Object.entries(custom.renamed ?? {}).toSorted(byKey);
|
|
540
|
-
const shared = sharedRoleSql(ctx);
|
|
541
|
-
if (custom.levels === true) {
|
|
542
|
-
chunks.push(leveledKeysSql(ctx, renames));
|
|
543
|
-
if (shared !== "") chunks.push(shared);
|
|
544
|
-
return chunks.join("\n\n");
|
|
545
|
-
}
|
|
546
|
-
const rename = renamesSql(renames);
|
|
547
|
-
chunks.push(`-- one custom role: included ceiling keys and same-scope denies, plus every ceiling key of an allowed permission, minus denied permissions
|
|
548
|
-
create or replace function ${keys}(p_allow text[], p_deny text[], p_include text[], p_scope text)
|
|
549
|
-
returns setof text
|
|
550
|
-
language sql
|
|
551
|
-
stable
|
|
552
|
-
set search_path = ''
|
|
553
|
-
as $$
|
|
554
|
-
with ${rename.prelude}ceiling as (
|
|
555
|
-
select c.role, ${rename.permission("c")}, c.grant_key, c.effect
|
|
556
|
-
from ${ceiling} c${rename.join("c")}
|
|
557
|
-
where c.scope = p_scope
|
|
558
|
-
),
|
|
559
|
-
included as (
|
|
560
|
-
select rp.role, ${rename.permission("rp")}, rp.grant_key, rp.scope, rp.effect
|
|
561
|
-
from ${rp} rp${rename.join("rp")}
|
|
562
|
-
where rp.role = any(coalesce(p_include, '{}'::text[]))
|
|
563
|
-
),
|
|
564
|
-
kept as (
|
|
565
|
-
select i.permission, i.grant_key
|
|
566
|
-
from included i
|
|
567
|
-
where i.effect = 'allow'
|
|
568
|
-
and i.scope = p_scope
|
|
569
|
-
and exists (
|
|
570
|
-
select 1 from ceiling c
|
|
571
|
-
where c.role = i.role and c.grant_key = i.grant_key and c.effect = 'allow'
|
|
572
|
-
)
|
|
573
|
-
),
|
|
574
|
-
wanted as (
|
|
575
|
-
${rename.allow}
|
|
576
|
-
union
|
|
577
|
-
select i.permission
|
|
578
|
-
from included i
|
|
579
|
-
where i.effect = 'allow'
|
|
580
|
-
and not (i.scope = p_scope and exists (
|
|
581
|
-
select 1 from ceiling c
|
|
582
|
-
where c.role = i.role and c.grant_key = i.grant_key and c.effect = 'allow'
|
|
583
|
-
))
|
|
584
|
-
),
|
|
585
|
-
allowed as (
|
|
586
|
-
select w.permission
|
|
587
|
-
from wanted w
|
|
588
|
-
where not (${rename.denied("w")})
|
|
589
|
-
and not exists (select 1 from kept k where k.permission = w.permission)
|
|
590
|
-
)
|
|
591
|
-
select k.grant_key from kept k
|
|
592
|
-
where not (${rename.denied("k")})
|
|
593
|
-
union
|
|
594
|
-
select i.grant_key from included i
|
|
595
|
-
where i.effect = 'deny' and i.scope = p_scope
|
|
596
|
-
union
|
|
597
|
-
select c.grant_key from ceiling c
|
|
598
|
-
where c.permission in (select a.permission from allowed a)
|
|
599
|
-
$$;
|
|
600
|
-
revoke execute on function ${keys}(text[], text[], text[], text) from public, anon, authenticated;`);
|
|
601
|
-
if (shared !== "") chunks.push(shared);
|
|
602
|
-
return chunks.join("\n\n");
|
|
603
|
-
}
|
|
604
|
-
/**
|
|
605
|
-
* `permdock_is_shared_role(p_scope, p_role)` (`database` mode): whether a
|
|
606
|
-
* shared custom role of that name exists at the scope.
|
|
607
|
-
*/
|
|
608
|
-
function sharedRoleSql(ctx) {
|
|
609
|
-
if (ctx.authorize !== "database") return "";
|
|
610
|
-
const perms = qualified(ctx, CUSTOM_ROLES.permissions);
|
|
611
|
-
const includes = qualified(ctx, CUSTOM_ROLES.includes);
|
|
612
|
-
const shared = qualified(ctx, CUSTOM_ROLES.shared);
|
|
613
|
-
return `-- a shared custom role: rows with no tenant at a scope below global; its name wins over a tenant role's in every tenant
|
|
614
|
-
create or replace function ${shared}(p_scope text, p_role text)
|
|
615
|
-
returns boolean
|
|
616
|
-
language sql
|
|
617
|
-
stable
|
|
618
|
-
security definer
|
|
619
|
-
set search_path = ''
|
|
620
|
-
as $$
|
|
621
|
-
select p_scope <> 'global' and (
|
|
622
|
-
exists (select 1 from ${perms} c where c.tenant_id is null and c.scope = p_scope and c.role = p_role)
|
|
623
|
-
or exists (select 1 from ${includes} c where c.tenant_id is null and c.scope = p_scope and c.role = p_role)
|
|
624
|
-
)
|
|
625
|
-
$$;
|
|
626
|
-
revoke execute on function ${shared}(text, text) from public, anon, authenticated;`;
|
|
627
|
-
}
|
|
628
|
-
/**
|
|
629
|
-
* `permdock_custom_keys` when resources declare levels. An allow entry is `key`
|
|
630
|
-
* or `key@level`. A level reaches only the ceiling's `<grant key>@<level>`
|
|
631
|
-
* keys, plus the ceiling denies of that permission; a level no ceiling key
|
|
632
|
-
* carries removes the permission, as `resolveCustomRole` drops it with
|
|
633
|
-
* `unknown-level`.
|
|
634
|
-
*/
|
|
635
|
-
function leveledKeysSql(ctx, renames) {
|
|
636
|
-
const rp = qualified(ctx, "role_permissions");
|
|
637
|
-
const ceiling = qualified(ctx, CUSTOM_ROLES.ceiling);
|
|
638
|
-
const keys = qualified(ctx, CUSTOM_ROLES.keys);
|
|
639
|
-
const renamed = renames.length > 0;
|
|
640
|
-
const prelude = renamed ? `renamed (former, key) as (values ${renames.map(([former, current]) => `(${quoteLiteral(former)}, ${quoteLiteral(current)})`).join(", ")}),
|
|
641
|
-
` : "";
|
|
642
|
-
const current = (raw, alias) => renamed ? `coalesce(r_${alias}.key, ${raw})` : raw;
|
|
643
|
-
const join = (raw, alias) => renamed ? ` left join renamed r_${alias} on r_${alias}.former = ${raw}` : "";
|
|
644
|
-
return `-- one custom role: as above, where an allow entry key@level reaches only the ceiling keys of that level
|
|
645
|
-
create or replace function ${keys}(p_allow text[], p_deny text[], p_include text[], p_scope text)
|
|
646
|
-
returns setof text
|
|
647
|
-
language sql
|
|
648
|
-
stable
|
|
649
|
-
set search_path = ''
|
|
650
|
-
as $$
|
|
651
|
-
with ${prelude}entries as (
|
|
652
|
-
select ${current("split_part(e.entry, '@', 1)", "e")} as permission, nullif(split_part(e.entry, '@', 2), '') as level
|
|
653
|
-
from unnest(coalesce(p_allow, '{}'::text[])) as e(entry)${join("split_part(e.entry, '@', 1)", "e")}
|
|
654
|
-
),
|
|
655
|
-
ceiling as (
|
|
656
|
-
select c.role, ${current("c.permission", "c")} as permission, c.grant_key, c.effect
|
|
657
|
-
from ${ceiling} c${join("c.permission", "c")}
|
|
658
|
-
where c.scope = p_scope
|
|
659
|
-
),
|
|
660
|
-
levels as (
|
|
661
|
-
select distinct c.permission, split_part(c.grant_key, '@', 2) as level
|
|
662
|
-
from ceiling c
|
|
663
|
-
where c.effect = 'allow' and strpos(c.grant_key, '@') > 0
|
|
664
|
-
),
|
|
665
|
-
denied as (
|
|
666
|
-
select ${current("d.permission", "d")} as permission
|
|
667
|
-
from unnest(coalesce(p_deny, '{}'::text[])) as d(permission)${join("d.permission", "d")}
|
|
668
|
-
union
|
|
669
|
-
select e.permission from entries e
|
|
670
|
-
where e.level is not null
|
|
671
|
-
and not exists (select 1 from levels l where l.permission = e.permission and l.level = e.level)
|
|
672
|
-
),
|
|
673
|
-
included as (
|
|
674
|
-
select rp.role, ${current("rp.permission", "rp")} as permission, rp.grant_key, rp.scope, rp.effect
|
|
675
|
-
from ${rp} rp${join("rp.permission", "rp")}
|
|
676
|
-
where rp.role = any(coalesce(p_include, '{}'::text[]))
|
|
677
|
-
),
|
|
678
|
-
kept as (
|
|
679
|
-
select i.permission, i.grant_key
|
|
680
|
-
from included i
|
|
681
|
-
where i.effect = 'allow'
|
|
682
|
-
and i.scope = p_scope
|
|
683
|
-
and exists (
|
|
684
|
-
select 1 from ceiling c
|
|
685
|
-
where c.role = i.role and c.grant_key = i.grant_key and c.effect = 'allow'
|
|
686
|
-
)
|
|
687
|
-
),
|
|
688
|
-
wanted as (
|
|
689
|
-
select e.permission from entries e where e.level is null
|
|
690
|
-
union
|
|
691
|
-
select i.permission
|
|
692
|
-
from included i
|
|
693
|
-
where i.effect = 'allow'
|
|
694
|
-
and not (i.scope = p_scope and exists (
|
|
695
|
-
select 1 from ceiling c
|
|
696
|
-
where c.role = i.role and c.grant_key = i.grant_key and c.effect = 'allow'
|
|
697
|
-
))
|
|
698
|
-
),
|
|
699
|
-
allowed as (
|
|
700
|
-
select w.permission
|
|
701
|
-
from wanted w
|
|
702
|
-
where w.permission not in (select d.permission from denied d)
|
|
703
|
-
and not exists (select 1 from kept k where k.permission = w.permission)
|
|
704
|
-
),
|
|
705
|
-
allowed_levels as (
|
|
706
|
-
select e.permission, e.level
|
|
707
|
-
from entries e
|
|
708
|
-
where e.level is not null
|
|
709
|
-
and e.permission not in (select d.permission from denied d)
|
|
710
|
-
and e.permission not in (select a.permission from allowed a)
|
|
711
|
-
and not exists (select 1 from kept k where k.permission = e.permission)
|
|
712
|
-
)
|
|
713
|
-
select k.grant_key from kept k
|
|
714
|
-
where k.permission not in (select d.permission from denied d)
|
|
715
|
-
union
|
|
716
|
-
select i.grant_key from included i
|
|
717
|
-
where i.effect = 'deny' and i.scope = p_scope
|
|
718
|
-
union
|
|
719
|
-
select c.grant_key from ceiling c
|
|
720
|
-
where c.permission in (select a.permission from allowed a)
|
|
721
|
-
union
|
|
722
|
-
select c.grant_key from ceiling c
|
|
723
|
-
join allowed_levels a on a.permission = c.permission
|
|
724
|
-
where c.effect = 'deny' or split_part(c.grant_key, '@', 2) = a.level
|
|
725
|
-
$$;
|
|
726
|
-
revoke execute on function ${keys}(text[], text[], text[], text) from public, anon, authenticated;`;
|
|
727
|
-
}
|
|
728
|
-
function currentKeysSql(array) {
|
|
729
|
-
return `select coalesce(r.key, e.permission) as permission
|
|
730
|
-
from unnest(coalesce(${array}, '{}'::text[])) as e(permission)
|
|
731
|
-
left join renamed r on r.former = e.permission`;
|
|
732
|
-
}
|
|
733
|
-
/**
|
|
734
|
-
* SQL fragments that read a stored former key as its current key inside
|
|
735
|
-
* `permdock_custom_keys`. Without renames they are the plain column and array
|
|
736
|
-
* reads.
|
|
737
|
-
*/
|
|
738
|
-
function renamesSql(renames) {
|
|
739
|
-
if (renames.length === 0) return {
|
|
740
|
-
prelude: "",
|
|
741
|
-
permission: (alias) => `${alias}.permission`,
|
|
742
|
-
join: () => "",
|
|
743
|
-
allow: "select unnest(coalesce(p_allow, '{}'::text[])) as permission",
|
|
744
|
-
denied: (alias) => `${alias}.permission = any(coalesce(p_deny, '{}'::text[]))`
|
|
745
|
-
};
|
|
746
|
-
return {
|
|
747
|
-
prelude: `renamed (former, key) as (values ${renames.map(([former, current]) => `(${quoteLiteral(former)}, ${quoteLiteral(current)})`).join(", ")}),
|
|
748
|
-
denied as (
|
|
749
|
-
${currentKeysSql("p_deny")}
|
|
750
|
-
),
|
|
751
|
-
`,
|
|
752
|
-
permission: (alias) => `coalesce(r_${alias}.key, ${alias}.permission) as permission`,
|
|
753
|
-
join: (alias) => ` left join renamed r_${alias} on r_${alias}.former = ${alias}.permission`,
|
|
754
|
-
allow: currentKeysSql("p_allow"),
|
|
755
|
-
denied: (alias) => `${alias}.permission in (select d.permission from denied d)`
|
|
756
|
-
};
|
|
757
|
-
}
|
|
758
|
-
/**
|
|
759
|
-
* The catalog reader `permdock_permission_keys()` and the role reader
|
|
760
|
-
* `permdock_role_permissions(p_role, p_scope, p_tenant, p_scope_id)`, both for
|
|
761
|
-
* `authenticated`. A declared role answers from `role_permissions`, which is
|
|
762
|
-
* the catalog. A custom role (`database` mode) answers from the tenant's own
|
|
763
|
-
* rows through `permdock_custom_keys`, only to a member of the tenant or a
|
|
764
|
-
* holder of a `meta.manageRoles` permission for a platform role; a shared role
|
|
765
|
-
* (no tenant below global) to any signed-in caller. The effect is `deny` for a
|
|
766
|
-
* deny the role carries after the ceiling, as `resolveCustomRole` returns it,
|
|
767
|
-
* never for a deny that merely removes an allow.
|
|
768
|
-
*/
|
|
769
|
-
function roleReadersSql(ctx, permissions, trustedReaders) {
|
|
770
|
-
const rp = qualified(ctx, "role_permissions");
|
|
771
|
-
const reader = qualified(ctx, READERS.roles);
|
|
772
|
-
const tenantType = tenantTypeOf(ctx);
|
|
773
|
-
const custom = ctx.customRoles;
|
|
774
|
-
const root = ctx.scopes[0]?.name;
|
|
775
|
-
const database = ctx.authorize === "database";
|
|
776
|
-
const chunks = [];
|
|
777
|
-
if (permissions !== void 0) {
|
|
778
|
-
const catalog = qualified(ctx, READERS.keys);
|
|
779
|
-
chunks.push(`-- every declared permission key
|
|
780
|
-
create or replace function ${catalog}()
|
|
781
|
-
returns setof text
|
|
782
|
-
language sql
|
|
783
|
-
stable
|
|
784
|
-
set search_path = ''
|
|
785
|
-
as $$
|
|
786
|
-
select k.permission from unnest(${sqlTextArray(permissions.toSorted())}) k(permission) order by 1
|
|
787
|
-
$$;
|
|
788
|
-
revoke execute on function ${catalog}() from public, anon;
|
|
789
|
-
grant execute on function ${catalog}() to authenticated;
|
|
790
|
-
|
|
791
|
-
create or replace function ${catalog}(p_scope text)
|
|
792
|
-
returns setof text
|
|
793
|
-
language sql
|
|
794
|
-
stable
|
|
795
|
-
security definer
|
|
796
|
-
set search_path = ''
|
|
797
|
-
as $$
|
|
798
|
-
select distinct rp.permission
|
|
799
|
-
from ${rp} rp
|
|
800
|
-
where rp.scope = p_scope
|
|
801
|
-
and rp.effect = 'allow'
|
|
802
|
-
and rp.permission = any(${sqlTextArray(permissions.toSorted())})
|
|
803
|
-
order by 1
|
|
804
|
-
$$;
|
|
805
|
-
revoke execute on function ${catalog}(text) from public, anon;
|
|
806
|
-
grant execute on function ${catalog}(text) to authenticated;`);
|
|
807
|
-
}
|
|
808
|
-
const declared = ` select distinct rp.permission, rp.effect
|
|
809
|
-
from ${rp} rp
|
|
810
|
-
where rp.role = p_role and rp.scope = p_scope
|
|
811
|
-
order by 1, 2`;
|
|
812
|
-
let body = `begin
|
|
813
|
-
perform p_tenant, p_scope_id; -- only a custom role reads them
|
|
814
|
-
return query
|
|
815
|
-
${declared};
|
|
816
|
-
end;`;
|
|
817
|
-
let trustedBody = body;
|
|
818
|
-
if (custom !== void 0 && database && root !== void 0) {
|
|
819
|
-
const tenant = qualified(ctx, CUSTOM_ROLES.permissions);
|
|
820
|
-
const includes = qualified(ctx, CUSTOM_ROLES.includes);
|
|
821
|
-
const keys = qualified(ctx, CUSTOM_ROLES.keys);
|
|
822
|
-
const shape = qualified(ctx, CUSTOM_ROLES.shape);
|
|
823
|
-
const ids = (helper) => `(select x::text from ${qualified(ctx, helper)}() x)`;
|
|
824
|
-
const memberOf = `p_tenant::text in ${ids(memberIdsHelper(root))}
|
|
825
|
-
or ${perScope(ctx, (scope) => scope === root ? "false" : `p_scope_id in ${ids(memberIdsHelper(scope))}`)}`;
|
|
826
|
-
const manage = custom.manage ?? [];
|
|
827
|
-
const platform = manage.length === 0 ? "false" : `exists (
|
|
828
|
-
select 1 from ${rp} m
|
|
829
|
-
where m.effect = 'allow'
|
|
830
|
-
and m.permission = any(${sqlTextArray(manage)})
|
|
831
|
-
and ${qualified(ctx, HELPERS.has)}(m.grant_key)
|
|
832
|
-
)`;
|
|
833
|
-
const match = `c.tenant_id is not distinct from p_tenant and c.scope = p_scope and c.scope_id is not distinct from p_scope_id and c.role = p_role`;
|
|
834
|
-
const allowEntryOf = `c.${allowEntry(ctx)}`;
|
|
835
|
-
const checked = (gate) => `begin
|
|
836
|
-
if p_role = any(${sqlTextArray(custom.declared)}) then
|
|
837
|
-
return query
|
|
838
|
-
${declared};
|
|
839
|
-
return;
|
|
840
|
-
end if;
|
|
841
|
-
perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);${gate}
|
|
842
|
-
return query
|
|
843
|
-
select distinct rp.permission, rp.effect
|
|
844
|
-
from ${keys}(
|
|
845
|
-
array(select ${allowEntryOf} from ${tenant} c where ${match} and c.effect = 'allow'),
|
|
846
|
-
array(select c.permission from ${tenant} c where ${match} and c.effect = 'deny'),
|
|
847
|
-
array(select c.include_role from ${includes} c where ${match}),
|
|
848
|
-
p_scope
|
|
849
|
-
) k(grant_key)
|
|
850
|
-
join ${rp} rp on rp.grant_key = k.grant_key and rp.scope = p_scope
|
|
851
|
-
order by 1, 2;
|
|
852
|
-
end;`;
|
|
853
|
-
body = checked(`
|
|
854
|
-
if not (${signedIn(ctx)} and (
|
|
855
|
-
${platform}
|
|
856
|
-
or (p_scope <> 'global' and p_tenant is null and p_scope_id is null)
|
|
857
|
-
or (p_scope <> 'global' and (${memberOf}))
|
|
858
|
-
)) then
|
|
859
|
-
${raiseSql(" ", "42501", `'permdock: the caller is not a member of ' || coalesce(p_tenant::text, 'the platform')`, "not-member")}
|
|
860
|
-
end if;`);
|
|
861
|
-
trustedBody = checked("");
|
|
862
|
-
}
|
|
863
|
-
chunks.push(`-- the permission keys a role holds on a scope, with effect allow or deny; a custom role is read for its tenant and, below the first scope, its instance
|
|
864
|
-
create or replace function ${reader}(p_role text, p_scope text, p_tenant ${tenantType} default null, p_scope_id text default null)
|
|
865
|
-
returns table (permission text, effect text)
|
|
866
|
-
language plpgsql
|
|
867
|
-
stable
|
|
868
|
-
security definer
|
|
869
|
-
set search_path = ''
|
|
870
|
-
as $$
|
|
871
|
-
${body}
|
|
872
|
-
$$;
|
|
873
|
-
revoke execute on function ${reader}(text, text, ${tenantType}, text) from public, anon;
|
|
874
|
-
grant execute on function ${reader}(text, text, ${tenantType}, text) to authenticated;`);
|
|
875
|
-
const trusted = qualified(ctx, READERS.trusted);
|
|
876
|
-
const signature = `text, text, ${tenantType}, text`;
|
|
877
|
-
const grants = trustedReaders === void 0 || trustedReaders.length === 0 ? "" : `\n${trustedReaderGrants(ctx, `${trusted}(${signature})`, trustedReaders)}`;
|
|
878
|
-
chunks.push(`create or replace function ${trusted}(p_role text, p_scope text, p_tenant ${tenantType} default null, p_scope_id text default null)
|
|
879
|
-
returns table (permission text, effect text)
|
|
880
|
-
language plpgsql
|
|
881
|
-
stable
|
|
882
|
-
security definer
|
|
883
|
-
set search_path = ''
|
|
884
|
-
as $$
|
|
885
|
-
${trustedBody}
|
|
886
|
-
$$;
|
|
887
|
-
revoke execute on function ${trusted}(${signature}) from public, anon, authenticated;${grants}`);
|
|
888
|
-
return chunks.join("\n\n");
|
|
889
|
-
}
|
|
890
|
-
/**
|
|
891
|
-
* The stored definition of `p_role` at `p_scope` for `p_tenant`: the shared
|
|
892
|
-
* rows when a shared role has the name.
|
|
893
|
-
*/
|
|
894
|
-
function storedTenant(ctx) {
|
|
895
|
-
return `case when ${qualified(ctx, CUSTOM_ROLES.shared)}(p_scope, p_role) then c.tenant_id is null else c.tenant_id is not distinct from p_tenant end`;
|
|
896
|
-
}
|
|
897
|
-
/**
|
|
898
|
-
* The tenant half of a custom-role row match for a membership: the membership's
|
|
899
|
-
* tenant, or no tenant when a shared role of that name exists at the scope, so
|
|
900
|
-
* a shared role shadows a tenant role of the same name.
|
|
901
|
-
*/
|
|
902
|
-
function customTenantMatch(ctx, tenant, scope, role) {
|
|
903
|
-
return `case when ${qualified(ctx, CUSTOM_ROLES.shared)}(${quoteLiteral(scope)}, ${role}) then c.tenant_id is null else c.tenant_id::text = ${tenant} end`;
|
|
904
|
-
}
|
|
905
|
-
/**
|
|
906
|
-
* The scope of a row of the application's roles table: its scope column (or the
|
|
907
|
-
* first scope) with a tenant; with no tenant, the same scope when the `shared`
|
|
908
|
-
* column is true, else `'global'`.
|
|
909
|
-
*/
|
|
910
|
-
function rolesTableScope(table, tenant, root, column) {
|
|
911
|
-
const own = table.scope === void 0 ? quoteLiteral(root) : `${column(table.scope)}::text`;
|
|
912
|
-
return `case when ${tenant} is null then ${table.shared === void 0 ? "'global'" : `case when coalesce(${column(table.shared)}, false) then ${own} else 'global' end`} else ${own} end`;
|
|
913
|
-
}
|
|
914
|
-
/**
|
|
915
|
-
* `expr` read as its current key: a former key maps to the key it was renamed
|
|
916
|
-
* to.
|
|
917
|
-
*/
|
|
918
|
-
function currentKeyExpr(renames, expr) {
|
|
919
|
-
if (renames.length === 0) return expr;
|
|
920
|
-
return `(case ${expr} ${renames.map(([former, current]) => `when ${quoteLiteral(former)} then ${quoteLiteral(current)}`).join(" ")} else ${expr} end)`;
|
|
921
|
-
}
|
|
922
|
-
/**
|
|
923
|
-
* `case p_scope when '<scope>' then <sql for scope> ... else false end` over
|
|
924
|
-
* the declared scopes.
|
|
925
|
-
*/
|
|
926
|
-
function perScope(ctx, sql) {
|
|
927
|
-
const arms = ctx.scopes.map((scope) => `when ${quoteLiteral(scope.name)} then ${sql(scope.name)}`).join(" ");
|
|
928
|
-
return arms === "" ? "false" : `(case p_scope ${arms} else false end)`;
|
|
929
|
-
}
|
|
930
|
-
function raiseSql(indent, errcode, message, hint) {
|
|
931
|
-
return `${indent}raise exception using
|
|
932
|
-
${indent} errcode = '${errcode}',
|
|
933
|
-
${indent} message = ${message},
|
|
934
|
-
${indent} hint = ${quoteLiteral(hint)};`;
|
|
935
|
-
}
|
|
936
|
-
function hasCustomRoleChecksFor(ctx) {
|
|
937
|
-
return ctx.authorize === "database" && ctx.customRoles !== void 0 && ctx.scopes.length > 0 && ctx.scopes.every((scope) => hasMemberFor(ctx, scope.name));
|
|
938
|
-
}
|
|
939
|
-
/**
|
|
940
|
-
* The grants a `rls.trustedReaders` role needs for one reader: usage on the
|
|
941
|
-
* helper schema, which no client role reaches through these lines, and execute
|
|
942
|
-
* on the function.
|
|
943
|
-
*/
|
|
944
|
-
function trustedReaderGrants(ctx, fn, readers) {
|
|
945
|
-
const to = readers.map(quoteIdent).join(", ");
|
|
946
|
-
return `grant usage on schema ${quoteIdent(helperSchema(ctx))} to ${to};
|
|
947
|
-
grant execute on function ${fn} to ${to};`;
|
|
948
|
-
}
|
|
949
|
-
//#endregion
|
|
950
|
-
//#region src/cli/sql/global-roles.ts
|
|
951
|
-
function qualify(name, schema) {
|
|
952
|
-
return name.includes(".") ? name : `${schema}.${name}`;
|
|
953
|
-
}
|
|
954
|
-
function throughTenant(through, roles) {
|
|
955
|
-
if (through === void 0 || roles?.tenant === void 0) return;
|
|
956
|
-
return qualify(roles.table, "public") === through.table ? roles.tenant : void 0;
|
|
957
|
-
}
|
|
958
|
-
/**
|
|
959
|
-
* Resolves `source` against `schema`, aliasing the table `alias` and the roles
|
|
960
|
-
* table `<alias>k`.
|
|
961
|
-
*/
|
|
962
|
-
function globalRoleSource(source, schema, alias, roles) {
|
|
963
|
-
const table = qualify(source.table, schema);
|
|
964
|
-
const user = source.user ?? "user_id";
|
|
965
|
-
const role = roleColumn(source.role ?? "role", table, alias, {
|
|
966
|
-
label: "roles.role",
|
|
967
|
-
prefix: "PermDock CLI",
|
|
968
|
-
indent: " "
|
|
969
|
-
});
|
|
970
|
-
const tenant = role.lateral ? void 0 : throughTenant(role.through, roles);
|
|
971
|
-
const shared = tenant === void 0 ? void 0 : roles?.shared;
|
|
972
|
-
const global = tenant === void 0 ? "" : ` and ${alias}k.${quoteIdent(tenant)} is null${shared === void 0 ? "" : ` and ${alias}k.${quoteIdent(shared)} is not true`}`;
|
|
973
|
-
return {
|
|
974
|
-
table,
|
|
975
|
-
user,
|
|
976
|
-
from: `${quoteTable(table)} ${alias}${role.join}${global}`,
|
|
977
|
-
userSql: `${alias}.${quoteIdent(user)}`,
|
|
978
|
-
roleSql: role.sql,
|
|
979
|
-
nullable: role.nullable,
|
|
980
|
-
role: roleManifest(role),
|
|
981
|
-
...role.through === void 0 ? {} : { through: role.through },
|
|
982
|
-
...tenant === void 0 ? {} : { tenant },
|
|
983
|
-
...shared === void 0 ? {} : { shared }
|
|
984
|
-
};
|
|
985
|
-
}
|
|
986
|
-
//#endregion
|
|
987
|
-
//#region src/cli/rls/helper-rows.ts
|
|
988
|
-
function activeTenant(ctx) {
|
|
989
|
-
return `nullif(${subjectClaimSql(ctx, ctx.tenantClaim)}, '')`;
|
|
990
|
-
}
|
|
991
|
-
function keyTenantLine(ctx, scope, tenant) {
|
|
992
|
-
const keyed = keyTenantSql(ctx, underRoot(ctx, scope) ? tenant : void 0);
|
|
993
|
-
return keyed === void 0 ? "" : `\n and ${keyed}`;
|
|
994
|
-
}
|
|
995
|
-
/**
|
|
996
|
-
* Whether the helper for `scope` narrows to the tenant claim: unless
|
|
997
|
-
* `rls.tenants` is `'all'`, when the first scope is on its chain.
|
|
998
|
-
*/
|
|
999
|
-
function narrowsTo(ctx, scope) {
|
|
1000
|
-
return ctx.tenants !== "all" && underRoot(ctx, scope);
|
|
1001
|
-
}
|
|
1002
|
-
/**
|
|
1003
|
-
* Whether the active tenant narrows memberships of `scope`: the first scope is
|
|
1004
|
-
* on its chain.
|
|
1005
|
-
*/
|
|
1006
|
-
function underRoot(ctx, scope) {
|
|
1007
|
-
const root = ctx.scopes[0]?.name;
|
|
1008
|
-
let current = ctx.scopes.find((item) => item.name === scope);
|
|
1009
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1010
|
-
while (current !== void 0 && !seen.has(current.name)) {
|
|
1011
|
-
if (current.name === root) return true;
|
|
1012
|
-
seen.add(current.name);
|
|
1013
|
-
const parent = current.within;
|
|
1014
|
-
current = parent === void 0 ? void 0 : ctx.scopes.find((item) => item.name === parent);
|
|
1015
|
-
}
|
|
1016
|
-
return false;
|
|
1017
|
-
}
|
|
1018
|
-
/**
|
|
1019
|
-
* `and exists (...)` lines for an active user; empty without
|
|
1020
|
-
* `rls.suspension.users`.
|
|
1021
|
-
*/
|
|
1022
|
-
function userActive(ctx, indent, user) {
|
|
1023
|
-
return activeUserSql(ctx, user).map((part) => `${indent}and ${part}`);
|
|
1024
|
-
}
|
|
1025
|
-
/**
|
|
1026
|
-
* `and exists (...)` lines for every suspendable instance on the chain of
|
|
1027
|
-
* `scope`'s membership.
|
|
1028
|
-
*/
|
|
1029
|
-
function instancesActive(ctx, scope, idOf, indent, permission) {
|
|
1030
|
-
return activeInstancesSql(ctx, scope, idOf, permission).map((part) => `${indent}and ${part}`);
|
|
1031
|
-
}
|
|
1032
|
-
function roleRows(ctx) {
|
|
1033
|
-
const claim = ctx.roleClaim ?? "user_role";
|
|
1034
|
-
switch (ctx.dialect) {
|
|
1035
|
-
case "guc": return `unnest(string_to_array(nullif(current_setting(${quoteLiteral(`${ctx.gucPrefix}.${claim}`)}, true), ''), ',')) r(role)`;
|
|
1036
|
-
case "supabase":
|
|
1037
|
-
case "neon": {
|
|
1038
|
-
const raw = subjectClaimJsonSql(ctx, claim);
|
|
1039
|
-
const value = ctx.dialect === "supabase" ? `coalesce(nullif(${raw}, 'null'::jsonb), (select auth.jwt()) -> 'app_metadata' -> ${quoteLiteral(claim)})` : raw;
|
|
1040
|
-
return `jsonb_array_elements_text(
|
|
1041
|
-
case jsonb_typeof(${value})
|
|
1042
|
-
when 'array' then ${value}
|
|
1043
|
-
when 'string' then jsonb_build_array(${value})
|
|
1044
|
-
else '[]'::jsonb
|
|
1045
|
-
end
|
|
1046
|
-
) r(role)`;
|
|
1047
|
-
}
|
|
1048
|
-
default: return ctx.dialect;
|
|
1049
|
-
}
|
|
1050
|
-
}
|
|
1051
|
-
function membershipRows(ctx) {
|
|
1052
|
-
const raw = subjectClaimJsonSql(ctx, "memberships");
|
|
1053
|
-
const value = ctx.dialect === "supabase" ? `coalesce(${raw}, (select auth.jwt()) -> 'app_metadata' -> 'memberships')` : raw;
|
|
1054
|
-
return `jsonb_array_elements(
|
|
1055
|
-
case jsonb_typeof(${value}) when 'array' then ${value} else '[]'::jsonb end
|
|
1056
|
-
) m
|
|
1057
|
-
cross join lateral jsonb_array_elements_text(
|
|
1058
|
-
case jsonb_typeof(m -> 'roles') when 'array' then m -> 'roles' else '[]'::jsonb end
|
|
1059
|
-
) r(role)`;
|
|
1060
|
-
}
|
|
1061
|
-
function andLine(indent, condition) {
|
|
1062
|
-
return condition === void 0 ? "" : `\n${indent}and ${condition}`;
|
|
1063
|
-
}
|
|
1064
|
-
/** `rls.roles`, or the generated `user_roles (user_id, role)`, aliased `ur`. */
|
|
1065
|
-
function globalRoleRows(ctx) {
|
|
1066
|
-
return ctx.roles === void 0 ? {
|
|
1067
|
-
from: `${qualified(ctx, "user_roles")} ur`,
|
|
1068
|
-
userSql: "ur.user_id",
|
|
1069
|
-
roleSql: "ur.role::text"
|
|
1070
|
-
} : globalRoleSource(ctx.roles, "public", "ur", ctx.customRoles?.table);
|
|
1071
|
-
}
|
|
1072
|
-
function customKeysJoin(ctx, scope, allows, denies, includes) {
|
|
1073
|
-
return ` cross join lateral ${qualified(ctx, CUSTOM_ROLES.keys)}(
|
|
1074
|
-
${allows},
|
|
1075
|
-
${denies},
|
|
1076
|
-
${includes},
|
|
1077
|
-
${quoteLiteral(scope)}
|
|
1078
|
-
) ck(grant_key)`;
|
|
1079
|
-
}
|
|
1080
|
-
//#endregion
|
|
1081
|
-
//#region src/cli/rls/helper-bodies.ts
|
|
1082
|
-
function hasSetBody(ctx) {
|
|
1083
|
-
const rp = qualified(ctx, "role_permissions");
|
|
1084
|
-
const active = userActive(ctx, " ").map((line) => `\n${line}`).join("");
|
|
1085
|
-
const custom = ctx.customRoles;
|
|
1086
|
-
if (ctx.authorize === "database") {
|
|
1087
|
-
const ur = globalRoleRows(ctx);
|
|
1088
|
-
const declared = ` select rp.grant_key
|
|
1089
|
-
from ${ur.from}
|
|
1090
|
-
join ${rp} rp on rp.role = ${ur.roleSql}
|
|
1091
|
-
where ${ur.userSql} = ${subjectIdSql(ctx)}
|
|
1092
|
-
and rp.scope = 'global'${andLine(" ", globalKindFilterSql(ctx, ur.roleSql))}${active}`;
|
|
1093
|
-
if (custom === void 0) return declared;
|
|
1094
|
-
const match = `c.tenant_id is null and c.scope = 'global' and c.scope_id is null and c.role = ${ur.roleSql}`;
|
|
1095
|
-
const rows = (source, value, extra) => `array(select c.${value} from ${qualified(ctx, source)} c where ${match}${extra})`;
|
|
1096
|
-
return `${declared}
|
|
1097
|
-
union
|
|
1098
|
-
select ck.grant_key
|
|
1099
|
-
from ${ur.from}
|
|
1100
|
-
${customKeysJoin(ctx, "global", rows(CUSTOM_ROLES.permissions, allowEntry(ctx), " and c.effect = 'allow'"), rows(CUSTOM_ROLES.permissions, "permission", " and c.effect = 'deny'"), rows(CUSTOM_ROLES.includes, "include_role", ""))}
|
|
1101
|
-
where ${ur.userSql} = ${subjectIdSql(ctx)}
|
|
1102
|
-
and not (${ur.roleSql} = any(${sqlTextArray(custom.declared)}))${active}`;
|
|
1103
|
-
}
|
|
1104
|
-
const declared = ` select rp.grant_key
|
|
1105
|
-
from ${roleRows(ctx)}
|
|
1106
|
-
join ${rp} rp on rp.role = r.role
|
|
1107
|
-
where ${signedIn(ctx)}
|
|
1108
|
-
and rp.scope = 'global'${andLine(" ", globalKindFilterSql(ctx, "r.role"))}${active}`;
|
|
1109
|
-
if (custom === void 0) return declared;
|
|
1110
|
-
const claim = subjectClaimJsonSql(ctx, GLOBAL_GRANTS_CLAIM);
|
|
1111
|
-
return `${declared}
|
|
1112
|
-
union
|
|
1113
|
-
select ck.grant_key
|
|
1114
|
-
from ${roleRows(ctx)}
|
|
1115
|
-
cross join lateral (select ${claim} -> r.role as g) cg
|
|
1116
|
-
${customKeysJoin(ctx, "global", claimEntries("left(e, 1) not in ('-', '@')", "e"), claimEntries("left(e, 1) = '-'", "substr(e, 2)"), claimEntries("left(e, 1) = '@'", "substr(e, 2)"))}
|
|
1117
|
-
where ${signedIn(ctx)}
|
|
1118
|
-
and jsonb_typeof(cg.g) = 'array'
|
|
1119
|
-
and not (r.role = any(${sqlTextArray(custom.declared)}))${active}`;
|
|
1120
|
-
}
|
|
1121
|
-
function hasBody(ctx) {
|
|
1122
|
-
if (ctx.grantSet === true) return hasSetBody(ctx);
|
|
1123
|
-
const rp = qualified(ctx, "role_permissions");
|
|
1124
|
-
const active = userActive(ctx, " ").map((line) => `\n${line}`).join("");
|
|
1125
|
-
const custom = ctx.customRoles;
|
|
1126
|
-
if (ctx.authorize === "database") {
|
|
1127
|
-
const ur = globalRoleRows(ctx);
|
|
1128
|
-
const declared = ` select exists (
|
|
1129
|
-
select 1
|
|
1130
|
-
from ${ur.from}
|
|
1131
|
-
join ${rp} rp on rp.role = ${ur.roleSql}
|
|
1132
|
-
where ${ur.userSql} = ${subjectIdSql(ctx)}
|
|
1133
|
-
and rp.grant_key = p_grant
|
|
1134
|
-
and rp.scope = 'global'${andLine(" ", globalKindFilterSql(ctx, ur.roleSql))}${active}
|
|
1135
|
-
)`;
|
|
1136
|
-
if (custom === void 0) return declared;
|
|
1137
|
-
const match = `c.tenant_id is null and c.scope = 'global' and c.scope_id is null and c.role = ${ur.roleSql}`;
|
|
1138
|
-
const rows = (source, value, extra) => `array(select c.${value} from ${qualified(ctx, source)} c where ${match}${extra})`;
|
|
1139
|
-
return `${declared}
|
|
1140
|
-
or exists (
|
|
1141
|
-
select 1
|
|
1142
|
-
from ${ur.from}
|
|
1143
|
-
where ${ur.userSql} = ${subjectIdSql(ctx)}
|
|
1144
|
-
and not (${ur.roleSql} = any(${sqlTextArray(custom.declared)}))${active}
|
|
1145
|
-
${customKeysSql(ctx, "global", rows(CUSTOM_ROLES.permissions, allowEntry(ctx), " and c.effect = 'allow'"), rows(CUSTOM_ROLES.permissions, "permission", " and c.effect = 'deny'"), rows(CUSTOM_ROLES.includes, "include_role", "")).trimStart()}
|
|
1146
|
-
)`;
|
|
1147
|
-
}
|
|
1148
|
-
const declared = ` select ${signedIn(ctx)} and exists (
|
|
1149
|
-
select 1
|
|
1150
|
-
from ${roleRows(ctx)}
|
|
1151
|
-
join ${rp} rp on rp.role = r.role
|
|
1152
|
-
where rp.grant_key = p_grant
|
|
1153
|
-
and rp.scope = 'global'${andLine(" ", globalKindFilterSql(ctx, "r.role"))}${active}
|
|
1154
|
-
)`;
|
|
1155
|
-
if (custom === void 0) return declared;
|
|
1156
|
-
const claim = subjectClaimJsonSql(ctx, GLOBAL_GRANTS_CLAIM);
|
|
1157
|
-
return `${declared}
|
|
1158
|
-
or (${signedIn(ctx)} and exists (
|
|
1159
|
-
select 1
|
|
1160
|
-
from ${roleRows(ctx)}
|
|
1161
|
-
cross join lateral (select ${claim} -> r.role as g) cg
|
|
1162
|
-
where jsonb_typeof(cg.g) = 'array'
|
|
1163
|
-
and not (r.role = any(${sqlTextArray(custom.declared)}))${active}
|
|
1164
|
-
${customKeysSql(ctx, "global", claimEntries("left(e, 1) not in ('-', '@')", "e"), claimEntries("left(e, 1) = '-'", "substr(e, 2)"), claimEntries("left(e, 1) = '@'", "substr(e, 2)")).trimStart()}
|
|
1165
|
-
))`;
|
|
1166
|
-
}
|
|
1167
|
-
/**
|
|
1168
|
-
* The claim `jwt` mode reads platform custom roles from:
|
|
1169
|
-
* `customRoleClaim(globalRoles)`.
|
|
1170
|
-
*/
|
|
1171
|
-
const GLOBAL_GRANTS_CLAIM = "role_grants";
|
|
1172
|
-
function memberColumn(name) {
|
|
1173
|
-
return `m.${quoteIdent(name)}`;
|
|
1174
|
-
}
|
|
1175
|
-
function disabledColumn(table) {
|
|
1176
|
-
return table.disabledAt === void 0 ? void 0 : memberColumn(table.disabledAt);
|
|
1177
|
-
}
|
|
1178
|
-
function claimKeptLines(ctx, indent, permission) {
|
|
1179
|
-
return disabledKeep(ctx).length === 0 ? [] : [`${indent}and ${keptRowSql("m -> 'keep'", permission)}`];
|
|
1180
|
-
}
|
|
1181
|
-
/** Entries of a compact custom-role claim (`cg.g`) that match `where`. */
|
|
1182
|
-
function claimEntries(where, value) {
|
|
1183
|
-
return `array(select ${value} from jsonb_array_elements_text(cg.g) e where ${where})`;
|
|
1184
|
-
}
|
|
1185
|
-
/** `p_grant in (select permdock_custom_keys(allows, denies, includes, scope))`. */
|
|
1186
|
-
function customKeysSql(ctx, scope, allows, denies, includes) {
|
|
1187
|
-
return ` and p_grant in (select ${qualified(ctx, CUSTOM_ROLES.keys)}(
|
|
1188
|
-
${allows},
|
|
1189
|
-
${denies},
|
|
1190
|
-
${includes},
|
|
1191
|
-
${quoteLiteral(scope)}
|
|
1192
|
-
))`;
|
|
1193
|
-
}
|
|
1194
|
-
function tableFilters(ctx, scope, table, tenantColumn, grant) {
|
|
1195
|
-
const filters = [];
|
|
1196
|
-
if (table.expiresAt !== void 0) {
|
|
1197
|
-
const expires = memberColumn(table.expiresAt);
|
|
1198
|
-
filters.push(` and (${expires} is null or ${expires} > now())`);
|
|
1199
|
-
}
|
|
1200
|
-
filters.push(...activeMembershipSql(ctx, disabledColumn(table), grantPermissionSql(grant)).map((part) => ` and ${part}`));
|
|
1201
|
-
if (tenantColumn !== void 0 && ctx.tenants !== "all") filters.push(` and (${activeTenant(ctx)} is null or ${memberColumn(tenantColumn)}::text = ${activeTenant(ctx)})`);
|
|
1202
|
-
const keyed = keyTenantSql(ctx, tenantColumn === void 0 ? void 0 : memberColumn(tenantColumn));
|
|
1203
|
-
if (keyed !== void 0) filters.push(` and ${keyed}`);
|
|
1204
|
-
const user = activeUserChecks(ctx, memberColumn(table.user), "act_user", " ");
|
|
1205
|
-
const instances = activeInstanceChecks(ctx, scope, (name) => {
|
|
1206
|
-
const held = scopeColumn(table, ctx.scopes, name);
|
|
1207
|
-
return held === void 0 ? void 0 : memberColumn(held);
|
|
1208
|
-
}, (name) => `act_${name}`, " ", grantPermissionSql(grant));
|
|
1209
|
-
filters.push(...instances.filters.map((part) => ` and ${part}`));
|
|
1210
|
-
return {
|
|
1211
|
-
owner: ` where ${memberColumn(table.user)} = ${subjectIdSql(ctx)}`,
|
|
1212
|
-
joins: [...user.joins, ...instances.joins],
|
|
1213
|
-
filters
|
|
1214
|
-
};
|
|
1215
|
-
}
|
|
1216
|
-
function tableBranch(ctx, scope, type, table, column, tenantColumn, branch, set, declared, stale) {
|
|
1217
|
-
const checks = tableFilters(ctx, scope, table, tenantColumn, branch === "custom" && set ? "ck.grant_key" : set ? "rp.grant_key" : "p_grant");
|
|
1218
|
-
const role = memberRoleOf(table, "m", " ");
|
|
1219
|
-
const kind = kindFilterSql(ctx, role.sql, memberVia(table));
|
|
1220
|
-
const gate = stale === true ? [` and not (select ${qualified(ctx, HELPERS.tokenCurrent)}())`] : [];
|
|
1221
|
-
const custom = ctx.customRoles;
|
|
1222
|
-
return [
|
|
1223
|
-
branch === "declared" ? ` select${role.lateral ? " distinct" : ""} ${memberColumn(column)}::${type}${set ? ", rp.grant_key" : ""}` : ` select ${memberColumn(column)}::${type}${set ? ", ck.grant_key" : ""}`,
|
|
1224
|
-
` from ${quoteQualified(table.table)} m${role.join}`,
|
|
1225
|
-
...checks.joins,
|
|
1226
|
-
...branch === "custom" && set && custom !== void 0 ? [customKeysJoin(ctx, scope, ...customEntries(ctx, scope, column, tenantColumn, role.sql))] : [],
|
|
1227
|
-
...branch === "declared" ? [` join ${qualified(ctx, "role_permissions")} rp on rp.role = ${role.sql}`] : [],
|
|
1228
|
-
checks.owner,
|
|
1229
|
-
...gate,
|
|
1230
|
-
...branch === "declared" ? [
|
|
1231
|
-
...set ? [] : [" and rp.grant_key = p_grant"],
|
|
1232
|
-
` and rp.scope = ${quoteLiteral(scope)}`,
|
|
1233
|
-
...kind === void 0 ? [] : [` and ${kind}`]
|
|
1234
|
-
] : [` and not (${role.sql} = any(${sqlTextArray(declared)}))`],
|
|
1235
|
-
...checks.filters,
|
|
1236
|
-
...branch === "custom" && !set && custom !== void 0 ? [customKeysSql(ctx, scope, ...customEntries(ctx, scope, column, tenantColumn, role.sql))] : []
|
|
1237
|
-
].join("\n");
|
|
1238
|
-
}
|
|
1239
|
-
function customEntries(ctx, scope, column, tenantColumn, roleSql) {
|
|
1240
|
-
const match = [
|
|
1241
|
-
customTenantMatch(ctx, `${memberColumn(tenantColumn ?? column)}::text`, scope, roleSql),
|
|
1242
|
-
`c.scope = ${quoteLiteral(scope)}`,
|
|
1243
|
-
`(c.scope_id is null or c.scope_id = ${memberColumn(column)}::text)`,
|
|
1244
|
-
`c.role = ${roleSql}`
|
|
1245
|
-
].join(" and ");
|
|
1246
|
-
const rows = (source, value, extra) => `array(select c.${value} from ${qualified(ctx, source)} c where ${match}${extra})`;
|
|
1247
|
-
return [
|
|
1248
|
-
rows(CUSTOM_ROLES.permissions, allowEntry(ctx), " and c.effect = 'allow'"),
|
|
1249
|
-
rows(CUSTOM_ROLES.permissions, "permission", " and c.effect = 'deny'"),
|
|
1250
|
-
rows(CUSTOM_ROLES.includes, "include_role", "")
|
|
1251
|
-
];
|
|
1252
|
-
}
|
|
1253
|
-
function tableBody(ctx, scope, type) {
|
|
1254
|
-
const mapped = scopeTable(ctx, scope);
|
|
1255
|
-
if (mapped === void 0) return ` select null::${type} where false -- no ${scope} memberships table configured`;
|
|
1256
|
-
const { table, column, tenantColumn } = mapped;
|
|
1257
|
-
const set = ctx.grantSet === true;
|
|
1258
|
-
const custom = ctx.customRoles;
|
|
1259
|
-
const branches = [];
|
|
1260
|
-
if (ctx.claimsFirst === true && !set) {
|
|
1261
|
-
branches.push(claimDeclaredBody(ctx, scope, type));
|
|
1262
|
-
branches.push(tableBranch(ctx, scope, type, table, column, tenantColumn, "declared", set, [], true));
|
|
1263
|
-
} else branches.push(tableBranch(ctx, scope, type, table, column, tenantColumn, "declared", set, []));
|
|
1264
|
-
if (custom !== void 0) branches.push(tableBranch(ctx, scope, type, table, column, tenantColumn, "custom", set, custom.declared));
|
|
1265
|
-
return branches.join("\n union\n");
|
|
1266
|
-
}
|
|
1267
|
-
/** The membership's instance of the first scope, from the canonical claim. */
|
|
1268
|
-
function claimTenant(ctx, scope) {
|
|
1269
|
-
const root = rootName(ctx);
|
|
1270
|
-
return scope === root ? `m ->> 'id'` : `m -> 'within' ->> ${quoteLiteral(root)}`;
|
|
1271
|
-
}
|
|
1272
|
-
function claimDeclaredBody(ctx, scope, type) {
|
|
1273
|
-
const grant = "p_grant";
|
|
1274
|
-
const narrow = narrowsTo(ctx, scope) ? `\n and (${activeTenant(ctx)} is null or ${claimTenant(ctx, scope)} = ${activeTenant(ctx)})` : "";
|
|
1275
|
-
const user = activeUserChecks(ctx, subjectIdSql(ctx), "act_user", " ");
|
|
1276
|
-
const instances = activeInstanceChecks(ctx, scope, (name) => name === scope ? `m ->> 'id'` : `m -> 'within' ->> ${quoteLiteral(name)}`, (name) => `act_${name}`, " ", grantPermissionSql(grant));
|
|
1277
|
-
const filters = [
|
|
1278
|
-
` and (select ${qualified(ctx, HELPERS.tokenCurrent)}())`,
|
|
1279
|
-
` and m ->> 'scope' = ${quoteLiteral(scope)}`,
|
|
1280
|
-
` and m ->> 'id' is not null${narrow}${keyTenantLine(ctx, scope, claimTenant(ctx, scope))}`,
|
|
1281
|
-
` and case jsonb_typeof(m -> 'expires_at')
|
|
1282
|
-
when 'number' then (m ->> 'expires_at')::numeric > extract(epoch from now())
|
|
1283
|
-
else true
|
|
1284
|
-
end`,
|
|
1285
|
-
...claimKeptLines(ctx, " ", grantPermissionSql(grant)),
|
|
1286
|
-
...instances.filters.map((part) => ` and ${part}`)
|
|
1287
|
-
];
|
|
1288
|
-
const kind = kindFilterSql(ctx, "r.role", "m ->> 'via'");
|
|
1289
|
-
return [
|
|
1290
|
-
` select (m ->> 'id')::${type}`,
|
|
1291
|
-
` from ${membershipRows(ctx)}`,
|
|
1292
|
-
...user.joins,
|
|
1293
|
-
...instances.joins,
|
|
1294
|
-
` join ${qualified(ctx, "role_permissions")} rp on rp.role = r.role`,
|
|
1295
|
-
` where ${signedIn(ctx)}`,
|
|
1296
|
-
` and rp.grant_key = p_grant`,
|
|
1297
|
-
` and rp.scope = ${quoteLiteral(scope)}`,
|
|
1298
|
-
...kind === void 0 ? [] : [` and ${kind}`],
|
|
1299
|
-
...filters
|
|
1300
|
-
].join("\n");
|
|
1301
|
-
}
|
|
1302
|
-
function claimBody(ctx, scope, type) {
|
|
1303
|
-
const set = ctx.grantSet === true;
|
|
1304
|
-
const narrow = narrowsTo(ctx, scope) ? `
|
|
1305
|
-
and (${activeTenant(ctx)} is null or ${claimTenant(ctx, scope)} = ${activeTenant(ctx)})` : "";
|
|
1306
|
-
const filtersFor = (grant) => ` and m ->> 'scope' = ${quoteLiteral(scope)}
|
|
1307
|
-
and m ->> 'id' is not null${narrow}${keyTenantLine(ctx, scope, claimTenant(ctx, scope))}
|
|
1308
|
-
and case jsonb_typeof(m -> 'expires_at')
|
|
1309
|
-
when 'number' then (m ->> 'expires_at')::numeric > extract(epoch from now())
|
|
1310
|
-
else true
|
|
1311
|
-
end${[
|
|
1312
|
-
...claimKeptLines(ctx, " ", grantPermissionSql(grant)),
|
|
1313
|
-
...userActive(ctx, " "),
|
|
1314
|
-
...instancesActive(ctx, scope, (name) => name === scope ? `m ->> 'id'` : `m -> 'within' ->> ${quoteLiteral(name)}`, " ", grantPermissionSql(grant))
|
|
1315
|
-
].map((line) => `\n${line}`).join("")}`;
|
|
1316
|
-
const filters = filtersFor(set ? "rp.grant_key" : "p_grant");
|
|
1317
|
-
const declared = ` select (m ->> 'id')::${type}${set ? ", rp.grant_key" : ""}
|
|
1318
|
-
from ${membershipRows(ctx)}
|
|
1319
|
-
join ${qualified(ctx, "role_permissions")} rp on rp.role = r.role
|
|
1320
|
-
where ${signedIn(ctx)}${set ? "" : "\n and rp.grant_key = p_grant"}
|
|
1321
|
-
and rp.scope = ${quoteLiteral(scope)}${andLine(" ", kindFilterSql(ctx, "r.role", "m ->> 'via'"))}
|
|
1322
|
-
${filters}`;
|
|
1323
|
-
const custom = ctx.customRoles;
|
|
1324
|
-
if (custom === void 0) return declared;
|
|
1325
|
-
if (set) return `${declared}
|
|
1326
|
-
union
|
|
1327
|
-
select (m ->> 'id')::${type}, ck.grant_key
|
|
1328
|
-
from ${membershipRows(ctx)}
|
|
1329
|
-
cross join lateral (select m -> 'grants' -> r.role as g) cg
|
|
1330
|
-
${customKeysJoin(ctx, scope, claimEntries("left(e, 1) not in ('-', '@')", "e"), claimEntries("left(e, 1) = '-'", "substr(e, 2)"), claimEntries("left(e, 1) = '@'", "substr(e, 2)"))}
|
|
1331
|
-
where ${signedIn(ctx)}
|
|
1332
|
-
and jsonb_typeof(cg.g) = 'array'
|
|
1333
|
-
and not (r.role = any(${sqlTextArray(custom.declared)}))
|
|
1334
|
-
${filtersFor("ck.grant_key")}`;
|
|
1335
|
-
return `${declared}
|
|
1336
|
-
union
|
|
1337
|
-
select (m ->> 'id')::${type}
|
|
1338
|
-
from ${membershipRows(ctx)}
|
|
1339
|
-
cross join lateral (select m -> 'grants' -> r.role as g) cg
|
|
1340
|
-
where ${signedIn(ctx)}
|
|
1341
|
-
and jsonb_typeof(cg.g) = 'array'
|
|
1342
|
-
and not (r.role = any(${sqlTextArray(custom.declared)}))
|
|
1343
|
-
${filters}
|
|
1344
|
-
${customKeysSql(ctx, scope, claimEntries("left(e, 1) not in ('-', '@')", "e"), claimEntries("left(e, 1) = '-'", "substr(e, 2)"), claimEntries("left(e, 1) = '@'", "substr(e, 2)"))}`;
|
|
1345
|
-
}
|
|
1346
|
-
/**
|
|
1347
|
-
* The rows the membership sources select for the subject, one per instance
|
|
1348
|
-
* (`scope`, `id`, `within`, `roles`, `via`), with each source's own expiry and
|
|
1349
|
-
* suspension filters: the statements the token hook runs.
|
|
1350
|
-
*/
|
|
1351
|
-
function sourcesKeep(sources) {
|
|
1352
|
-
return sources.some((source) => source.sql.keeps);
|
|
1353
|
-
}
|
|
1354
|
-
function sourceRows(sources) {
|
|
1355
|
-
const keep = sourcesKeep(sources);
|
|
1356
|
-
return sources.map((source, index) => source.sql.select(sourceUser(index), keep).replaceAll(/^/gmu, " ")).join("\n union all\n");
|
|
1357
|
-
}
|
|
1358
|
-
function sourceUser(index) {
|
|
1359
|
-
return `v_user_${String(index)}`;
|
|
1360
|
-
}
|
|
1361
|
-
function memoizes(ctx) {
|
|
1362
|
-
return ctx.authorize === "database" && ctx.dialect === "supabase" && ctx.grantSet !== true && ctx.subjectId === void 0;
|
|
1363
|
-
}
|
|
1364
|
-
function sqlBody(sql) {
|
|
1365
|
-
return {
|
|
1366
|
-
sql,
|
|
1367
|
-
vars: []
|
|
1368
|
-
};
|
|
1369
|
-
}
|
|
1370
|
-
function sourcesBodyOf(sql, sources, user) {
|
|
1371
|
-
return {
|
|
1372
|
-
sql,
|
|
1373
|
-
vars: sources.map((source, index) => `${sourceUser(index)} ${source.sql.userType} := ${user};`)
|
|
1374
|
-
};
|
|
1375
|
-
}
|
|
1376
|
-
/** SQL reading the memo at `key`: a text value, or null when unset. */
|
|
1377
|
-
function memoReadSql(api, key) {
|
|
1378
|
-
return api === "better-supabase" ? `better_supabase.memo_get(${key})` : `nullif(current_setting(${key}, true), '')`;
|
|
1379
|
-
}
|
|
1380
|
-
/** SQL writing `value` to the memo at `key`. */
|
|
1381
|
-
function memoWriteSql(api, key, value) {
|
|
1382
|
-
return api === "better-supabase" ? `better_supabase.memo_set(${key}, ${value})` : `set_config(${key}, ${value}, true)`;
|
|
1383
|
-
}
|
|
1384
|
-
function memoDiscriminatorSql(user, key) {
|
|
1385
|
-
return `md5(concat_ws('|',
|
|
1386
|
-
${user},
|
|
1387
|
-
${key},
|
|
1388
|
-
coalesce((select auth.jwt()) ->> 'authz_ver', ''),
|
|
1389
|
-
coalesce(nullif(current_setting('permdock.m.gen', true), ''), '0'),
|
|
1390
|
-
statement_timestamp()::text,
|
|
1391
|
-
md5(coalesce((select auth.jwt())::text, ''))
|
|
1392
|
-
))`;
|
|
1393
|
-
}
|
|
1394
|
-
/**
|
|
1395
|
-
* `language sql`, or `plpgsql` returning the query when the body declares
|
|
1396
|
-
* variables.
|
|
1397
|
-
*/
|
|
1398
|
-
function functionBody(body, parallelSafe = false) {
|
|
1399
|
-
const planner = `cost 1000${parallelSafe ? "\nparallel safe" : ""}`;
|
|
1400
|
-
if (body.memo !== void 0) {
|
|
1401
|
-
const declare = [
|
|
1402
|
-
...body.vars,
|
|
1403
|
-
`v_user text := ${body.memo.user}::text;`,
|
|
1404
|
-
`v_key text := 'permdock.m.' || ${quoteLiteral(body.memo.scope)} || '.k' || (hashtext(p_grant) & 1023)::text;`,
|
|
1405
|
-
`v_disc text := ${memoDiscriminatorSql("v_user", "p_grant")};`,
|
|
1406
|
-
`v_memo text := ${memoReadSql(body.memo.api, "v_key")};`
|
|
1407
|
-
];
|
|
1408
|
-
if (body.memo.type === "boolean") return `language plpgsql
|
|
1409
|
-
volatile
|
|
1410
|
-
security definer
|
|
1411
|
-
cost 1000
|
|
1412
|
-
set search_path = ''
|
|
1413
|
-
as $$
|
|
1414
|
-
declare
|
|
1415
|
-
${[...declare, "v_has boolean;"].map((line) => ` ${line}`).join("\n")}
|
|
1416
|
-
begin
|
|
1417
|
-
if v_memo is not null and (v_memo::jsonb ->> 'k') = v_disc then
|
|
1418
|
-
return (v_memo::jsonb ->> 'v')::boolean;
|
|
1419
|
-
end if;
|
|
1420
|
-
v_has := (
|
|
1421
|
-
${body.sql}
|
|
1422
|
-
);
|
|
1423
|
-
perform ${memoWriteSql(body.memo.api, "v_key", "jsonb_build_object('k', v_disc, 'v', v_has)::text")};
|
|
1424
|
-
return v_has;
|
|
1425
|
-
end;
|
|
1426
|
-
$$;`;
|
|
1427
|
-
declare.push(`v_ids ${body.memo.type}[];`);
|
|
1428
|
-
return `language plpgsql
|
|
1429
|
-
volatile
|
|
1430
|
-
security definer
|
|
1431
|
-
cost 1000
|
|
1432
|
-
set search_path = ''
|
|
1433
|
-
as $$
|
|
1434
|
-
declare
|
|
1435
|
-
${declare.map((line) => ` ${line}`).join("\n")}
|
|
1436
|
-
begin
|
|
1437
|
-
if v_memo is not null and (v_memo::jsonb ->> 'k') = v_disc then
|
|
1438
|
-
v_ids := array(select jsonb_array_elements_text(v_memo::jsonb -> 'ids')::${body.memo.type});
|
|
1439
|
-
else
|
|
1440
|
-
v_ids := array(
|
|
1441
|
-
${body.sql}
|
|
1442
|
-
);
|
|
1443
|
-
perform ${memoWriteSql(body.memo.api, "v_key", "jsonb_build_object('k', v_disc, 'ids', to_jsonb(v_ids))::text")};
|
|
1444
|
-
end if;
|
|
1445
|
-
return query select unnest(v_ids);
|
|
1446
|
-
end;
|
|
1447
|
-
$$;`;
|
|
1448
|
-
}
|
|
1449
|
-
if (body.vars.length === 0) return `language sql
|
|
1450
|
-
stable
|
|
1451
|
-
security definer
|
|
1452
|
-
${planner}
|
|
1453
|
-
set search_path = ''
|
|
1454
|
-
as $$
|
|
1455
|
-
${body.sql}
|
|
1456
|
-
$$;`;
|
|
1457
|
-
return `language plpgsql
|
|
1458
|
-
stable
|
|
1459
|
-
security definer
|
|
1460
|
-
${planner}
|
|
1461
|
-
set search_path = ''
|
|
1462
|
-
as $$
|
|
1463
|
-
declare
|
|
1464
|
-
${body.vars.map((line) => ` ${line}`).join("\n")}
|
|
1465
|
-
begin
|
|
1466
|
-
return query
|
|
1467
|
-
${body.sql};
|
|
1468
|
-
end;
|
|
1469
|
-
$$;`;
|
|
1470
|
-
}
|
|
1471
|
-
/**
|
|
1472
|
-
* `ms.id` for the scope itself and `ms.within ->> name` for an ancestor. The
|
|
1473
|
-
* alias is not `s`, which `activeRowSql` binds inside its `exists`.
|
|
1474
|
-
*/
|
|
1475
|
-
function sourceIdOf(scope) {
|
|
1476
|
-
return (name) => name === scope ? "ms.id" : `ms.within ->> ${quoteLiteral(name)}`;
|
|
1477
|
-
}
|
|
1478
|
-
function sourceFilters(ctx, scope, user = subjectIdSql(ctx), permission, keeps = false) {
|
|
1479
|
-
return [
|
|
1480
|
-
...keeps ? [` and ${keptRowSql("ms.keep", permission)}`] : [],
|
|
1481
|
-
...userActive(ctx, " ", user),
|
|
1482
|
-
...instancesActive(ctx, scope, sourceIdOf(scope), " ", permission)
|
|
1483
|
-
].map((line) => `\n${line}`).join("");
|
|
1484
|
-
}
|
|
1485
|
-
function sourcesBody(ctx, scope, type) {
|
|
1486
|
-
const root = rootName(ctx);
|
|
1487
|
-
const tenant = sourceIdOf(scope)(root);
|
|
1488
|
-
const narrow = narrowsTo(ctx, scope) ? `\n and (${activeTenant(ctx)} is null or ${tenant} = ${activeTenant(ctx)})${keyTenantLine(ctx, scope, tenant)}` : keyTenantLine(ctx, scope, tenant);
|
|
1489
|
-
const sources = scopeSources(ctx, scope);
|
|
1490
|
-
const set = ctx.grantSet === true;
|
|
1491
|
-
const rows = ` from (
|
|
1492
|
-
${sourceRows(sources)}
|
|
1493
|
-
) ms
|
|
1494
|
-
cross join lateral jsonb_array_elements_text(
|
|
1495
|
-
case jsonb_typeof(ms.roles) when 'array' then ms.roles else '[]'::jsonb end
|
|
1496
|
-
) r(role)`;
|
|
1497
|
-
const declared = ` select (ms.id)::${type}${set ? ", rp.grant_key" : ""}
|
|
1498
|
-
${rows}
|
|
1499
|
-
join ${qualified(ctx, "role_permissions")} rp on rp.role = r.role
|
|
1500
|
-
where ${signedIn(ctx)}
|
|
1501
|
-
and ms.scope = ${quoteLiteral(scope)}${set ? "" : "\n and rp.grant_key = p_grant"}
|
|
1502
|
-
and rp.scope = ${quoteLiteral(scope)}${andLine(" ", kindFilterSql(ctx, "r.role", "ms.via"))}${narrow}${sourceFilters(ctx, scope, subjectIdSql(ctx), grantPermissionSql(set ? "rp.grant_key" : "p_grant"), sourcesKeep(sources))}`;
|
|
1503
|
-
const custom = ctx.customRoles;
|
|
1504
|
-
if (custom === void 0) return sourcesBodyOf(declared, sources, subjectIdSql(ctx));
|
|
1505
|
-
const match = [
|
|
1506
|
-
customTenantMatch(ctx, `(${tenant})::text`, scope, "r.role"),
|
|
1507
|
-
`c.scope = ${quoteLiteral(scope)}`,
|
|
1508
|
-
"(c.scope_id is null or c.scope_id = (ms.id)::text)",
|
|
1509
|
-
"c.role = r.role"
|
|
1510
|
-
].join(" and ");
|
|
1511
|
-
const entries = (source, value, extra) => `array(select c.${value} from ${qualified(ctx, source)} c where ${match}${extra})`;
|
|
1512
|
-
if (set) return sourcesBodyOf(`${declared}
|
|
1513
|
-
union
|
|
1514
|
-
select (ms.id)::${type}, ck.grant_key
|
|
1515
|
-
${rows}
|
|
1516
|
-
${customKeysJoin(ctx, scope, entries(CUSTOM_ROLES.permissions, allowEntry(ctx), " and c.effect = 'allow'"), entries(CUSTOM_ROLES.permissions, "permission", " and c.effect = 'deny'"), entries(CUSTOM_ROLES.includes, "include_role", ""))}
|
|
1517
|
-
where ${signedIn(ctx)}
|
|
1518
|
-
and ms.scope = ${quoteLiteral(scope)}
|
|
1519
|
-
and not (r.role = any(${sqlTextArray(custom.declared)}))${narrow}${sourceFilters(ctx, scope, subjectIdSql(ctx), grantPermissionSql("ck.grant_key"), sourcesKeep(sources))}`, sources, subjectIdSql(ctx));
|
|
1520
|
-
return sourcesBodyOf(`${declared}
|
|
1521
|
-
union
|
|
1522
|
-
select (ms.id)::${type}
|
|
1523
|
-
${rows}
|
|
1524
|
-
where ${signedIn(ctx)}
|
|
1525
|
-
and ms.scope = ${quoteLiteral(scope)}
|
|
1526
|
-
and not (r.role = any(${sqlTextArray(custom.declared)}))${narrow}${sourceFilters(ctx, scope, subjectIdSql(ctx), grantPermissionSql("p_grant"), sourcesKeep(sources))}
|
|
1527
|
-
${customKeysSql(ctx, scope, entries(CUSTOM_ROLES.permissions, allowEntry(ctx), " and c.effect = 'allow'"), entries(CUSTOM_ROLES.permissions, "permission", " and c.effect = 'deny'"), entries(CUSTOM_ROLES.includes, "include_role", ""))}`, sources, subjectIdSql(ctx));
|
|
1528
|
-
}
|
|
1529
|
-
function scopedBody(ctx, scope, type) {
|
|
1530
|
-
if (ctx.authorize !== "database") return sqlBody(claimBody(ctx, scope, type));
|
|
1531
|
-
return scopeSources(ctx, scope).length > 0 ? sourcesBody(ctx, scope, type) : sqlBody(tableBody(ctx, scope, type));
|
|
1532
|
-
}
|
|
1533
|
-
//#endregion
|
|
1534
|
-
//#region src/cli/rls/capabilities.ts
|
|
1535
|
-
/**
|
|
1536
|
-
* The helper `--capabilities` adds: ids of one resource a link capability claim
|
|
1537
|
-
* reaches. Part of the SQL contract.
|
|
1538
|
-
*/
|
|
1539
|
-
const CAPABILITIES = { ids: "permdock_capability_ids" };
|
|
1540
|
-
/**
|
|
1541
|
-
* The `anon` branch access for a resource-scoped grant reached through a link
|
|
1542
|
-
* capability: the row's `field` holds an id the capability claim names for
|
|
1543
|
-
* `resource`, `role` and `permission`. Uncorrelated, so it runs once per
|
|
1544
|
-
* statement; the column is compared as text because the claim holds text.
|
|
1545
|
-
*/
|
|
1546
|
-
function capabilityAccessSql(ctx, field, resource, role, permission) {
|
|
1547
|
-
const args = [
|
|
1548
|
-
resource,
|
|
1549
|
-
role,
|
|
1550
|
-
permission
|
|
1551
|
-
].map(quoteLiteral).join(", ");
|
|
1552
|
-
return `${quoteIdent(field)}::text in (select ${qualified(ctx, CAPABILITIES.ids)}(${args}))`;
|
|
1553
|
-
}
|
|
1554
|
-
function capabilitiesSql(ctx) {
|
|
1555
|
-
if (ctx.capabilities !== true) return "";
|
|
1556
|
-
const fn = qualified(ctx, CAPABILITIES.ids);
|
|
1557
|
-
return `-- link capabilities: the capability claim exchangeCapability mints (role anon, short-lived)
|
|
1558
|
-
create or replace function ${fn}(p_resource text, p_role text, p_permission text)
|
|
1559
|
-
returns setof text
|
|
1560
|
-
language sql
|
|
1561
|
-
stable
|
|
1562
|
-
set search_path = ''
|
|
1563
|
-
as $$
|
|
1564
|
-
select c -> 'on' ->> 'id'
|
|
1565
|
-
from (select ${subjectClaimJsonSql(ctx, "capability")} as c) capability
|
|
1566
|
-
where jsonb_typeof(c) = 'object'
|
|
1567
|
-
and c ->> 'v' = '1'
|
|
1568
|
-
and c ->> 'holder' = 'link'
|
|
1569
|
-
and c -> 'on' ->> 'resource' = p_resource
|
|
1570
|
-
and jsonb_typeof(c -> 'roles') = 'array'
|
|
1571
|
-
and c -> 'roles' @> jsonb_build_array(p_role)
|
|
1572
|
-
and (c -> 'permissions' is null or c -> 'permissions' @> jsonb_build_array(p_permission))
|
|
1573
|
-
and jsonb_typeof(c -> 'expires_at') = 'number'
|
|
1574
|
-
and (c ->> 'expires_at')::numeric > extract(epoch from now())
|
|
1575
|
-
$$;
|
|
1576
|
-
revoke execute on function ${fn}(text, text, text) from public;
|
|
1577
|
-
grant execute on function ${fn}(text, text, text) to anon, authenticated;`;
|
|
1578
|
-
}
|
|
1579
|
-
//#endregion
|
|
1580
|
-
//#region src/cli/rls/custom-role-by-id.ts
|
|
1581
|
-
const PREFIX = "PermDock CLI";
|
|
1582
|
-
const col = (name) => `r.${quoteIdent(name)}`;
|
|
1583
|
-
/**
|
|
1584
|
-
* Custom-role functions keyed by the application's role row
|
|
1585
|
-
* (`rls.customRoleWrites.roles.primaryKey`): the tenant, scope, instance and
|
|
1586
|
-
* name come from the row, never from the caller. The writers delegate to
|
|
1587
|
-
* `permdock_replace_custom_role_grants` (or its trusted variant), so every
|
|
1588
|
-
* caller and definition check applies, and keep the stored denies and includes.
|
|
1589
|
-
* The reader returns declared allow keys only and is executable by
|
|
1590
|
-
* `rls.trustedReaders` alone.
|
|
1591
|
-
*/
|
|
1592
|
-
function customRoleByIdSql(ctx, trustedReaders) {
|
|
1593
|
-
const custom = ctx.customRoles;
|
|
1594
|
-
const roles = custom?.table;
|
|
1595
|
-
const root = ctx.scopes[0]?.name;
|
|
1596
|
-
if (custom === void 0 || roles?.primaryKey === void 0 || ctx.authorize !== "database" || root === void 0) return "";
|
|
1597
|
-
const pk = roles.primaryKey;
|
|
1598
|
-
if (pk === "") throw configError(`${PREFIX}: rls.customRoleWrites.roles.primaryKey names no column`);
|
|
1599
|
-
const leveled = custom.levels === true;
|
|
1600
|
-
const tenantType = tenantTypeOf(ctx);
|
|
1601
|
-
const table = quoteQualified(roles.table);
|
|
1602
|
-
const idType = `${table}.${quoteIdent(pk)}%type`;
|
|
1603
|
-
const perms = qualified(ctx, CUSTOM_ROLES.permissions);
|
|
1604
|
-
const includes = qualified(ctx, CUSTOM_ROLES.includes);
|
|
1605
|
-
const replace = qualified(ctx, CUSTOM_ROLES.replace);
|
|
1606
|
-
const trustedReplace = qualified(ctx, CUSTOM_ROLES.trustedReplace);
|
|
1607
|
-
const byId = qualified(ctx, CUSTOM_ROLES.replaceById);
|
|
1608
|
-
const trustedById = qualified(ctx, CUSTOM_ROLES.trustedReplaceById);
|
|
1609
|
-
const reader = qualified(ctx, CUSTOM_ROLES.trustedReadById);
|
|
1610
|
-
const renames = Object.entries(custom.renamed ?? {}).toSorted(byKey);
|
|
1611
|
-
const current = (expr) => currentKeyExpr(renames, expr);
|
|
1612
|
-
const declaredKeys = sqlTextArray(custom.permissions ?? []);
|
|
1613
|
-
const declaredRoles = sqlTextArray(custom.declared);
|
|
1614
|
-
const tenant = roles.tenant === void 0 ? `null::${tenantType}` : `${col(roles.tenant)}::${tenantType}`;
|
|
1615
|
-
const scope = rolesTableScope(roles, tenant, root, col);
|
|
1616
|
-
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`;
|
|
1617
|
-
const skipped = roles.skip === void 0 || roles.tenant === void 0 ? "false" : `(${tenant} is not null and coalesce(${col(roles.skip)}, false))`;
|
|
1618
|
-
const match = "c.tenant_id is not distinct from v_tenant and c.scope = v_scope and c.scope_id is not distinct from v_scope_id and c.role = v_key";
|
|
1619
|
-
const audit = custom.audit;
|
|
1620
|
-
const auditCall = audit === void 0 ? "" : `
|
|
1621
|
-
perform ${quoteQualified(audit.function)}(${[
|
|
1622
|
-
"event_type => 'permdock.custom_role.replaced'",
|
|
1623
|
-
"target_type => 'role'",
|
|
1624
|
-
"record_id => p_role_id::text",
|
|
1625
|
-
"tenant => v_tenant",
|
|
1626
|
-
"metadata => jsonb_build_object('operation', 'replace', 'role', v_key, 'permissions', p_permissions)",
|
|
1627
|
-
...Object.entries(audit.args ?? {}).toSorted(byKey).map(([name, value]) => `${quoteIdent(name)} => ${quoteLiteral(value)}`)
|
|
1628
|
-
].join(", ")});`;
|
|
1629
|
-
const body = (write) => `declare
|
|
1630
|
-
v_tenant ${tenantType};
|
|
1631
|
-
v_scope text;
|
|
1632
|
-
v_scope_id text;
|
|
1633
|
-
v_key text;
|
|
1634
|
-
v_skipped boolean;
|
|
1635
|
-
v_deny text[];
|
|
1636
|
-
v_include text[];
|
|
1637
|
-
begin
|
|
1638
|
-
select ${tenant}, ${scope}, ${scopeId}, ${col(roles.key)}::text, ${skipped}
|
|
1639
|
-
into v_tenant, v_scope, v_scope_id, v_key, v_skipped
|
|
1640
|
-
from ${table} r
|
|
1641
|
-
where ${col(pk)} = p_role_id;
|
|
1642
|
-
if not found then
|
|
1643
|
-
${raiseSql(" ", "P0002", "'permdock: no role row has id ' || coalesce(p_role_id::text, 'null')", "unknown-role")}
|
|
1644
|
-
end if;
|
|
1645
|
-
if v_skipped or v_key = any(${declaredRoles}) then
|
|
1646
|
-
${raiseSql(" ", "22023", "'permdock: ' || coalesce(v_key, 'null') || ' is a declared role, not a custom role'", "declared-role")}
|
|
1647
|
-
end if;
|
|
1648
|
-
select array_agg(c.permission) into v_deny
|
|
1649
|
-
from ${perms} c
|
|
1650
|
-
where ${match} and c.effect = 'deny';
|
|
1651
|
-
select array_agg(c.include_role) into v_include
|
|
1652
|
-
from ${includes} c
|
|
1653
|
-
where ${match};
|
|
1654
|
-
perform ${write}(v_tenant, v_scope, v_scope_id, v_key, p_permissions, v_deny, v_include);${auditCall}
|
|
1655
|
-
end;`;
|
|
1656
|
-
const writer = (comment, name, write, member) => `-- ${comment}
|
|
1657
|
-
create or replace function ${name}(p_role_id ${idType}, p_permissions text[])
|
|
1658
|
-
returns void
|
|
1659
|
-
language plpgsql
|
|
1660
|
-
volatile
|
|
1661
|
-
security definer
|
|
1662
|
-
set search_path = ''
|
|
1663
|
-
as $$
|
|
1664
|
-
${body(write)}
|
|
1665
|
-
$$;
|
|
1666
|
-
${member ? `revoke execute on function ${name}(${idType}, text[]) from public, anon;
|
|
1667
|
-
grant execute on function ${name}(${idType}, text[]) to authenticated;` : `revoke execute on function ${name}(${idType}, text[]) from public, anon, authenticated;`}`;
|
|
1668
|
-
const readerEntry = leveled ? `${current("c.permission")} || coalesce('@' || c.level, '')` : current("c.permission");
|
|
1669
|
-
const readerGrant = trustedReaders === void 0 || trustedReaders.length === 0 ? "" : `\n${trustedReaderGrants(ctx, `${reader}(text[], ${tenantType})`, trustedReaders)}`;
|
|
1670
|
-
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)}
|
|
1671
|
-
|
|
1672
|
-
${writer("save a custom role by its row id for a trusted caller: the definition checks without the caller checks", trustedById, trustedReplace, false)}
|
|
1673
|
-
|
|
1674
|
-
-- 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
|
|
1675
|
-
create or replace function ${reader}(p_role_ids text[], p_tenant ${tenantType} default null)
|
|
1676
|
-
returns table (role_id text, permission text)
|
|
1677
|
-
language plpgsql
|
|
1678
|
-
stable
|
|
1679
|
-
security definer
|
|
1680
|
-
set search_path = ''
|
|
1681
|
-
as $$
|
|
1682
|
-
begin
|
|
1683
|
-
if p_tenant is not null and exists (
|
|
1684
|
-
select 1 from ${table} r
|
|
1685
|
-
where ${col(pk)}::text = any(p_role_ids) and ${tenant} is distinct from p_tenant
|
|
1686
|
-
) then
|
|
1687
|
-
${raiseSql(" ", "42501", "'permdock: a role id belongs to another tenant than ' || p_tenant::text", "not-member")}
|
|
1688
|
-
end if;
|
|
1689
|
-
return query
|
|
1690
|
-
select distinct v.role_id, ${readerEntry}
|
|
1691
|
-
from (
|
|
1692
|
-
select ${col(pk)}::text as role_id, ${tenant} as tenant_id, ${scope} as scope, ${scopeId} as scope_id, ${col(roles.key)}::text as role
|
|
1693
|
-
from ${table} r
|
|
1694
|
-
where ${col(pk)}::text = any(p_role_ids)
|
|
1695
|
-
and not ${skipped}
|
|
1696
|
-
and not (${col(roles.key)}::text = any(${declaredRoles}))
|
|
1697
|
-
) v
|
|
1698
|
-
join ${perms} c
|
|
1699
|
-
on c.tenant_id is not distinct from v.tenant_id
|
|
1700
|
-
and c.scope = v.scope
|
|
1701
|
-
and c.scope_id is not distinct from v.scope_id
|
|
1702
|
-
and c.role = v.role
|
|
1703
|
-
where c.effect = 'allow'
|
|
1704
|
-
and ${current("c.permission")} = any(${declaredKeys})
|
|
1705
|
-
order by 1, 2;
|
|
1706
|
-
end;
|
|
1707
|
-
$$;
|
|
1708
|
-
revoke execute on function ${reader}(text[], ${tenantType}) from public, anon, authenticated;${readerGrant}`;
|
|
1709
|
-
}
|
|
1710
|
-
//#endregion
|
|
1711
|
-
//#region src/cli/rls/custom-role-cascade.ts
|
|
1712
|
-
/** `row.column`, for a trigger's `old` or `new`. */
|
|
1713
|
-
function rowColumn(row, name) {
|
|
1714
|
-
return `${row}.${quoteIdent(name)}`;
|
|
1715
|
-
}
|
|
1716
|
-
/** The custom-role rows of the role a trigger's `v_<prefix>_*` variables name. */
|
|
1717
|
-
function cascadeMatch(prefix) {
|
|
1718
|
-
return `c.tenant_id is not distinct from v_${prefix}_tenant and c.scope = v_${prefix}_scope and c.scope_id is not distinct from v_${prefix}_id and c.role = v_${prefix}_key`;
|
|
1719
|
-
}
|
|
1720
|
-
/**
|
|
1721
|
-
* The trigger on the application's roles table (`rls.customRoleWrites.roles`):
|
|
1722
|
-
* a rename, a move to another tenant, scope or instance, or a delete of a
|
|
1723
|
-
* custom role's row carries its grants and includes along. A signed-in caller
|
|
1724
|
-
* at trigger depth 1 passes the write functions' checks: authority over the
|
|
1725
|
-
* stored definition where it was, and, after a move, membership and authority
|
|
1726
|
-
* where it lands and entries inside that scope's ceiling. Other paths (a
|
|
1727
|
-
* migration, a job, a nested trigger) move the rows as the function owner.
|
|
1728
|
-
*/
|
|
1729
|
-
function customRoleCascadeSql(ctx) {
|
|
1730
|
-
const custom = ctx.customRoles;
|
|
1731
|
-
const table = custom?.table;
|
|
1732
|
-
const root = ctx.scopes[0]?.name;
|
|
1733
|
-
if (custom === void 0 || table === void 0 || root === void 0) return "";
|
|
1734
|
-
const tenantType = tenantTypeOf(ctx);
|
|
1735
|
-
const perms = qualified(ctx, CUSTOM_ROLES.permissions);
|
|
1736
|
-
const includes = qualified(ctx, CUSTOM_ROLES.includes);
|
|
1737
|
-
const fn = qualified(ctx, CUSTOM_ROLES.cascade);
|
|
1738
|
-
const target = quoteTable(qualifySqlTable(table.table));
|
|
1739
|
-
const tenant = (row) => table.tenant === void 0 ? `null::${tenantType}` : `${rowColumn(row, table.tenant)}::${tenantType}`;
|
|
1740
|
-
const scope = (row) => rolesTableScope(table, tenant(row), root, (name) => rowColumn(row, name));
|
|
1741
|
-
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`;
|
|
1742
|
-
const skipped = (row) => table.skip === void 0 || table.tenant === void 0 ? "false" : `(${tenant(row)} is not null and coalesce(${rowColumn(row, table.skip)}, false))`;
|
|
1743
|
-
const guard = qualified(ctx, CUSTOM_ROLES.guard);
|
|
1744
|
-
const entries = qualified(ctx, CUSTOM_ROLES.entries);
|
|
1745
|
-
const allowEntryOf = `c.${allowEntry(ctx)}`;
|
|
1746
|
-
return `-- the application's roles table: renames, moves and deletes of a custom role carry its grants and includes
|
|
1747
|
-
create or replace function ${fn}()
|
|
1748
|
-
returns trigger
|
|
1749
|
-
language plpgsql
|
|
1750
|
-
volatile
|
|
1751
|
-
security definer
|
|
1752
|
-
set search_path = ''
|
|
1753
|
-
as $$
|
|
1754
|
-
declare
|
|
1755
|
-
v_old_tenant ${tenantType} := ${tenant("old")};
|
|
1756
|
-
v_old_scope text := ${scope("old")};
|
|
1757
|
-
v_old_id text := ${id("old")};
|
|
1758
|
-
v_old_key text := ${rowColumn("old", table.key)}::text;
|
|
1759
|
-
v_new_tenant ${tenantType};
|
|
1760
|
-
v_new_scope text;
|
|
1761
|
-
v_new_id text;
|
|
1762
|
-
v_new_key text;
|
|
1763
|
-
v_checked boolean := ${signedIn(ctx)} and pg_trigger_depth() = 1;
|
|
1764
|
-
v_allow text[];
|
|
1765
|
-
v_deny text[];
|
|
1766
|
-
v_include text[];
|
|
1767
|
-
begin
|
|
1768
|
-
if ${skipped("old")} then
|
|
1769
|
-
return null;
|
|
1770
|
-
end if;
|
|
1771
|
-
if tg_op = 'UPDATE' and not ${skipped("new")} then
|
|
1772
|
-
v_new_tenant := ${tenant("new")};
|
|
1773
|
-
v_new_scope := ${scope("new")};
|
|
1774
|
-
v_new_id := ${id("new")};
|
|
1775
|
-
v_new_key := ${rowColumn("new", table.key)}::text;
|
|
1776
|
-
if v_new_key = v_old_key
|
|
1777
|
-
and v_new_tenant is not distinct from v_old_tenant
|
|
1778
|
-
and v_new_scope = v_old_scope
|
|
1779
|
-
and v_new_id is not distinct from v_old_id then
|
|
1780
|
-
return null;
|
|
1781
|
-
end if;
|
|
1782
|
-
end if;
|
|
1783
|
-
if not exists (select 1 from ${perms} c where ${cascadeMatch("old")})
|
|
1784
|
-
and not exists (select 1 from ${includes} c where ${cascadeMatch("old")}) then
|
|
1785
|
-
return null;
|
|
1786
|
-
end if;
|
|
1787
|
-
if v_checked then
|
|
1788
|
-
perform ${guard}(v_old_tenant, v_old_scope, v_old_id, v_old_key);
|
|
1789
|
-
end if;
|
|
1790
|
-
if v_new_key is null then
|
|
1791
|
-
delete from ${perms} c where ${cascadeMatch("old")};
|
|
1792
|
-
delete from ${includes} c where ${cascadeMatch("old")};
|
|
1793
|
-
return null;
|
|
1794
|
-
end if;
|
|
1795
|
-
if exists (select 1 from ${perms} c where ${cascadeMatch("new")})
|
|
1796
|
-
or exists (select 1 from ${includes} c where ${cascadeMatch("new")}) then
|
|
1797
|
-
${raiseSql(" ", "22023", `'permdock: ' || v_new_key || ' already has grants'`, "role-exists")}
|
|
1798
|
-
end if;
|
|
1799
|
-
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")};
|
|
1800
|
-
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")};
|
|
1801
|
-
if v_checked then
|
|
1802
|
-
perform ${guard}(v_new_tenant, v_new_scope, v_new_id, v_new_key);
|
|
1803
|
-
select array_agg(${allowEntryOf}) filter (where c.effect = 'allow'),
|
|
1804
|
-
array_agg(c.permission) filter (where c.effect = 'deny')
|
|
1805
|
-
into v_allow, v_deny
|
|
1806
|
-
from ${perms} c
|
|
1807
|
-
where ${cascadeMatch("new")};
|
|
1808
|
-
select array_agg(c.include_role) into v_include
|
|
1809
|
-
from ${includes} c
|
|
1810
|
-
where ${cascadeMatch("new")};
|
|
1811
|
-
perform ${entries}(v_new_scope, v_allow, v_deny, v_include);
|
|
1812
|
-
end if;
|
|
1813
|
-
return null;
|
|
1814
|
-
end;
|
|
1815
|
-
$$;
|
|
1816
|
-
revoke execute on function ${fn}() from public, anon, authenticated;
|
|
1817
|
-
drop trigger if exists "permdock_custom_role_cascade" on ${target};
|
|
1818
|
-
create trigger "permdock_custom_role_cascade"
|
|
1819
|
-
after update or delete on ${target}
|
|
1820
|
-
for each row execute function ${fn}();
|
|
1821
|
-
`;
|
|
1822
|
-
}
|
|
1823
|
-
//#endregion
|
|
1824
|
-
//#region src/cli/rls/custom-role-guard.ts
|
|
1825
|
-
/** A column of the roles-table row a trigger sees as `new`. */
|
|
1826
|
-
function column(name) {
|
|
1827
|
-
return `new.${quoteIdent(name)}`;
|
|
1828
|
-
}
|
|
1829
|
-
/**
|
|
1830
|
-
* The trigger on the application's roles table (`rls.customRoleWrites.roles`)
|
|
1831
|
-
* that refuses a tenant row named like a declared role (`declared-role`) or
|
|
1832
|
-
* like a shared custom role (`name-taken`). A row the `skip` column marks is a
|
|
1833
|
-
* system role of the tenant and passes. Empty without a tenant column: then no
|
|
1834
|
-
* row is a tenant row.
|
|
1835
|
-
*/
|
|
1836
|
-
function customRoleNameGuardSql(ctx) {
|
|
1837
|
-
const custom = ctx.customRoles;
|
|
1838
|
-
const table = custom?.table;
|
|
1839
|
-
const root = ctx.scopes[0]?.name;
|
|
1840
|
-
if (custom === void 0 || table?.tenant === void 0 || root === void 0) return "";
|
|
1841
|
-
const tenant = `${column(table.tenant)}::${tenantTypeOf(ctx)}`;
|
|
1842
|
-
const skipped = table.skip === void 0 ? "false" : `coalesce(${column(table.skip)}, false)`;
|
|
1843
|
-
const fn = qualified(ctx, CUSTOM_ROLES.nameGuard);
|
|
1844
|
-
const target = quoteTable(qualifySqlTable(table.table));
|
|
1845
|
-
const key = `${column(table.key)}::text`;
|
|
1846
|
-
const scope = rolesTableScope(table, tenant, root, column);
|
|
1847
|
-
return `-- the application's roles table: a tenant row cannot take the name of a declared or a shared role
|
|
1848
|
-
create or replace function ${fn}()
|
|
1849
|
-
returns trigger
|
|
1850
|
-
language plpgsql
|
|
1851
|
-
volatile
|
|
1852
|
-
security definer
|
|
1853
|
-
set search_path = ''
|
|
1854
|
-
as $$
|
|
1855
|
-
begin
|
|
1856
|
-
if ${tenant} is null or ${skipped} then
|
|
1857
|
-
return new;
|
|
1858
|
-
end if;
|
|
1859
|
-
if ${key} = any(${sqlTextArray(custom.declared)}) then
|
|
1860
|
-
${raiseSql(" ", "22023", `'permdock: ' || ${key} || ' is a declared role'`, "declared-role")}
|
|
1861
|
-
end if;
|
|
1862
|
-
if ${qualified(ctx, CUSTOM_ROLES.shared)}(${scope}, ${key}) then
|
|
1863
|
-
${raiseSql(" ", "22023", `'permdock: ' || ${key} || ' is a shared role'`, "name-taken")}
|
|
1864
|
-
end if;
|
|
1865
|
-
return new;
|
|
1866
|
-
end;
|
|
1867
|
-
$$;
|
|
1868
|
-
revoke execute on function ${fn}() from public, anon, authenticated;
|
|
1869
|
-
drop trigger if exists "permdock_custom_role_name_guard" on ${target};
|
|
1870
|
-
create trigger "permdock_custom_role_name_guard"
|
|
1871
|
-
before insert or update on ${target}
|
|
1872
|
-
for each row execute function ${fn}();
|
|
1873
|
-
`;
|
|
1874
|
-
}
|
|
1875
|
-
//#endregion
|
|
1876
|
-
//#region src/cli/rls/custom-role-writes.ts
|
|
1877
|
-
function callerFunctionsSql(ctx, custom, root, levelReach, forUser) {
|
|
1878
|
-
const leveled = custom.levels === true;
|
|
1879
|
-
const tenantType = tenantTypeOf(ctx);
|
|
1880
|
-
const volatility = forUser || !memoizes(ctx) ? "stable" : "volatile";
|
|
1881
|
-
const rp = qualified(ctx, "role_permissions");
|
|
1882
|
-
const keys = qualified(ctx, CUSTOM_ROLES.keys);
|
|
1883
|
-
const perms = qualified(ctx, CUSTOM_ROLES.permissions);
|
|
1884
|
-
const includes = qualified(ctx, CUSTOM_ROLES.includes);
|
|
1885
|
-
const shape = qualified(ctx, CUSTOM_ROLES.shape);
|
|
1886
|
-
const beyond = qualified(ctx, forUser ? CUSTOM_ROLES.beyondFor : CUSTOM_ROLES.beyond);
|
|
1887
|
-
const guard = qualified(ctx, forUser ? CUSTOM_ROLES.guardFor : CUSTOM_ROLES.guard);
|
|
1888
|
-
const user = forUser ? "p_user" : subjectIdSql(ctx);
|
|
1889
|
-
const userParam = forUser ? "p_user uuid, " : "";
|
|
1890
|
-
const userArg = forUser ? "uuid, " : "";
|
|
1891
|
-
const userCall = forUser ? "p_user, " : "";
|
|
1892
|
-
const has = (key) => forUser ? `${qualified(ctx, HELPERS.hasFor)}(p_user, ${key})` : `${qualified(ctx, HELPERS.has)}(${key})`;
|
|
1893
|
-
const ids = (helper, arg) => `(select x::text from ${qualified(ctx, helper)}(${arg}) x)`;
|
|
1894
|
-
const permitted = (scope, key) => forUser ? ids(permittedForHelper(scope), `p_user, ${key}`) : ids(permittedIdsHelper(scope), key);
|
|
1895
|
-
const members = (scope) => forUser ? ids(memberForHelper(scope), "p_user") : ids(memberIdsHelper(scope), "");
|
|
1896
|
-
const heldKey = (key) => `(${has(key)}
|
|
1897
|
-
or (p_scope <> 'global'
|
|
1898
|
-
and (p_tenant::text in ${permitted(root, key)}
|
|
1899
|
-
or ${perScope(ctx, (scope) => scope === root ? "false" : `p_scope_id in ${permitted(scope, key)}`)})))`;
|
|
1900
|
-
const holdsAny = (permissions, held) => permissions.length === 0 ? "false" : `exists (
|
|
1901
|
-
select 1 from ${rp} rp
|
|
1902
|
-
where rp.effect = 'allow'
|
|
1903
|
-
and rp.permission = any(${sqlTextArray(permissions)})
|
|
1904
|
-
and ${held("rp.grant_key")}
|
|
1905
|
-
)`;
|
|
1906
|
-
const manageKeys = custom.manage ?? [];
|
|
1907
|
-
const manage = holdsAny(manageKeys, heldKey);
|
|
1908
|
-
const platform = holdsAny(manageKeys, has);
|
|
1909
|
-
const requires = custom.requires === void 0 ? "" : `
|
|
1910
|
-
if not ${holdsAny(custom.requires, heldKey)} then
|
|
1911
|
-
${raiseSql(" ", "42501", `'permdock: the caller may not manage roles in ' || coalesce(p_tenant::text, 'the platform')`, "manage-roles")}
|
|
1912
|
-
end if;`;
|
|
1913
|
-
const reachRows = levelReach.map(([grantKey, level]) => `(${quoteLiteral(grantKey)}, ${quoteLiteral(level)})`).join(", ");
|
|
1914
|
-
const levelCheck = leveled && reachRows !== "" ? `
|
|
1915
|
-
or exists (
|
|
1916
|
-
select 1
|
|
1917
|
-
from reach x
|
|
1918
|
-
where x.grant_key = r.grant_key
|
|
1919
|
-
and not exists (
|
|
1920
|
-
select 1 from held h
|
|
1921
|
-
join reach o on o.grant_key = h.grant_key
|
|
1922
|
-
where h.permission = r.permission and o.level = x.level
|
|
1923
|
-
)
|
|
1924
|
-
)` : "";
|
|
1925
|
-
const reachCte = leveled && reachRows !== "" ? `,
|
|
1926
|
-
reach (grant_key, level) as (values ${reachRows})` : "";
|
|
1927
|
-
const match = `${storedTenant(ctx)} and c.scope = p_scope and c.scope_id is not distinct from p_scope_id`;
|
|
1928
|
-
const memberOf = `p_tenant::text in ${members(root)}
|
|
1929
|
-
or ${perScope(ctx, (scope) => scope === root ? "false" : `p_scope_id in ${members(scope)}`)}`;
|
|
1930
|
-
return {
|
|
1931
|
-
beyond: `-- custom-role writes: the permission keys of a definition the caller may not hand out in the tenant, as assignablePermissions computes them
|
|
1932
|
-
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[])
|
|
1933
|
-
returns setof text
|
|
1934
|
-
language plpgsql
|
|
1935
|
-
${volatility}
|
|
1936
|
-
security definer
|
|
1937
|
-
set search_path = ''
|
|
1938
|
-
as $$
|
|
1939
|
-
begin
|
|
1940
|
-
if ${manage} then
|
|
1941
|
-
return;
|
|
1942
|
-
end if;
|
|
1943
|
-
return query
|
|
1944
|
-
with resolved as (
|
|
1945
|
-
select distinct rp.permission, k.key as grant_key
|
|
1946
|
-
from ${keys}(p_allow, p_deny, p_include, p_scope) k(key)
|
|
1947
|
-
join ${rp} rp on rp.grant_key = k.key and rp.effect = 'allow'
|
|
1948
|
-
),
|
|
1949
|
-
held as (
|
|
1950
|
-
select distinct rp.permission, rp.grant_key
|
|
1951
|
-
from ${rp} rp
|
|
1952
|
-
where rp.effect = 'allow'
|
|
1953
|
-
and rp.permission in (select r.permission from resolved r)
|
|
1954
|
-
and ${heldKey("rp.grant_key")}
|
|
1955
|
-
)${reachCte}
|
|
1956
|
-
select distinct r.permission
|
|
1957
|
-
from resolved r
|
|
1958
|
-
where not exists (select 1 from held h where h.permission = r.permission)${levelCheck};
|
|
1959
|
-
end;
|
|
1960
|
-
$$;
|
|
1961
|
-
revoke execute on function ${beyond}(${userArg}${tenantType}, text, text, text[], text[], text[]) from public, anon, authenticated;`,
|
|
1962
|
-
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
|
|
1963
|
-
create or replace function ${guard}(${userParam}p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text)
|
|
1964
|
-
returns void
|
|
1965
|
-
language plpgsql
|
|
1966
|
-
${volatility}
|
|
1967
|
-
security definer
|
|
1968
|
-
set search_path = ''
|
|
1969
|
-
as $$
|
|
1970
|
-
declare
|
|
1971
|
-
v_allow text[];
|
|
1972
|
-
v_deny text[];
|
|
1973
|
-
v_include text[];
|
|
1974
|
-
v_beyond text;
|
|
1975
|
-
begin
|
|
1976
|
-
perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);
|
|
1977
|
-
if not (${signedIn(ctx, user)} and (
|
|
1978
|
-
${platform}
|
|
1979
|
-
or (p_scope <> 'global' and coalesce(${memberOf}, false))
|
|
1980
|
-
)) then
|
|
1981
|
-
${raiseSql(" ", "42501", `'permdock: the caller is not a member of ' || coalesce(p_tenant::text, 'the platform')`, "not-member")}
|
|
1982
|
-
end if;${requires}
|
|
1983
|
-
select array_agg(${allowEntry(ctx)}) filter (where c.effect = 'allow'),
|
|
1984
|
-
array_agg(c.permission) filter (where c.effect = 'deny')
|
|
1985
|
-
into v_allow, v_deny
|
|
1986
|
-
from ${perms} c
|
|
1987
|
-
where ${match} and c.role = p_role;
|
|
1988
|
-
select array_agg(c.include_role) into v_include
|
|
1989
|
-
from ${includes} c
|
|
1990
|
-
where ${match} and c.role = p_role;
|
|
1991
|
-
select string_agg(b, ', ' order by b) into v_beyond
|
|
1992
|
-
from ${beyond}(${userCall}p_tenant, p_scope, p_scope_id, v_allow, v_deny, v_include) b;
|
|
1993
|
-
if v_beyond is not null then
|
|
1994
|
-
${raiseSql(" ", "42501", `'permdock: ' || p_role || ' allows ' || v_beyond || ', which the caller may not hand out'`, "not-assignable-by")}
|
|
1995
|
-
end if;
|
|
1996
|
-
end;
|
|
1997
|
-
$$;
|
|
1998
|
-
revoke execute on function ${guard}(${userArg}${tenantType}, text, text, text) from public, anon, authenticated;`
|
|
1999
|
-
};
|
|
2000
|
-
}
|
|
2001
|
-
/**
|
|
2002
|
-
* The functions an application calls to save, rename and delete a custom role
|
|
2003
|
-
* in \`database\` mode, with the rules of \`validateCustomRole\` and
|
|
2004
|
-
* \`assignablePermissions\`: entries inside the ceiling of the role's scope,
|
|
2005
|
-
* includes naming declared roles, and only permissions and levels the caller
|
|
2006
|
-
* may hand out, for the new definition and the stored one alike. A platform
|
|
2007
|
-
* custom role (\`p_scope = 'global'\`, no tenant) and a shared custom role (no
|
|
2008
|
-
* tenant at a lower scope) are written by a caller who holds a
|
|
2009
|
-
* \`meta.manageRoles\` permission through a global role. The
|
|
2010
|
-
* \`permdock_trusted_*\` variants skip the caller checks and keep the
|
|
2011
|
-
* definition checks; no client role may execute them.
|
|
2012
|
-
*/
|
|
2013
|
-
function customRoleWritesSql(ctx, levelReach) {
|
|
2014
|
-
const custom = ctx.customRoles;
|
|
2015
|
-
const root = ctx.scopes[0]?.name;
|
|
2016
|
-
if (custom === void 0 || ctx.authorize !== "database" || root === void 0) return "";
|
|
2017
|
-
const leveled = custom.levels === true;
|
|
2018
|
-
const tenantType = tenantTypeOf(ctx);
|
|
2019
|
-
const rp = qualified(ctx, "role_permissions");
|
|
2020
|
-
const ceiling = qualified(ctx, CUSTOM_ROLES.ceiling);
|
|
2021
|
-
const perms = qualified(ctx, CUSTOM_ROLES.permissions);
|
|
2022
|
-
const includes = qualified(ctx, CUSTOM_ROLES.includes);
|
|
2023
|
-
const beyond = qualified(ctx, CUSTOM_ROLES.beyond);
|
|
2024
|
-
const guard = qualified(ctx, CUSTOM_ROLES.guard);
|
|
2025
|
-
const shape = qualified(ctx, CUSTOM_ROLES.shape);
|
|
2026
|
-
const entries = qualified(ctx, CUSTOM_ROLES.entries);
|
|
2027
|
-
const problem = qualified(ctx, CUSTOM_ROLES.entryProblem);
|
|
2028
|
-
const renames = Object.entries(custom.renamed ?? {}).toSorted(byKey);
|
|
2029
|
-
const current = (expr) => currentKeyExpr(renames, expr);
|
|
2030
|
-
const known = sqlTextArray([...custom.permissions ?? [], ...renames.map(([former]) => former)]);
|
|
2031
|
-
const caller = callerFunctionsSql(ctx, custom, root, levelReach, false);
|
|
2032
|
-
const match = `c.tenant_id is not distinct from p_tenant and c.scope = p_scope and c.scope_id is not distinct from p_scope_id`;
|
|
2033
|
-
const scopes = sqlTextArray(ctx.scopes.map((scope) => scope.name));
|
|
2034
|
-
const roleName = (param) => `coalesce(${param}, '') = '' or ${param} = any(${sqlTextArray(custom.declared)})`;
|
|
2035
|
-
const levelOf = leveled ? ", nullif(split_part(e, '@', 2), '')" : "";
|
|
2036
|
-
const levelColumn = leveled ? ", level" : "";
|
|
2037
|
-
const sharedRole = qualified(ctx, CUSTOM_ROLES.shared);
|
|
2038
|
-
const taken = (param) => ` if p_tenant is not null and ${sharedRole}(p_scope, ${param}) then
|
|
2039
|
-
${raiseSql(" ", "22023", `'permdock: ' || ${param} || ' is the name of a shared custom role'`, "name-taken")}
|
|
2040
|
-
end if;
|
|
2041
|
-
`;
|
|
2042
|
-
const write = `${taken("p_role")} delete from ${perms} c where ${match} and c.role = p_role;
|
|
2043
|
-
delete from ${includes} c where ${match} and c.role = p_role;
|
|
2044
|
-
insert into ${perms} (tenant_id, scope, scope_id, role, permission, effect${levelColumn})
|
|
2045
|
-
select distinct p_tenant, p_scope, p_scope_id, p_role, ${current(leveled ? "split_part(e, '@', 1)" : "e")}, 'allow'${levelOf}
|
|
2046
|
-
from unnest(coalesce(p_allow, '{}'::text[])) e
|
|
2047
|
-
union
|
|
2048
|
-
select distinct p_tenant, p_scope, p_scope_id, p_role, ${current("e")}, 'deny'${leveled ? ", null" : ""}
|
|
2049
|
-
from unnest(coalesce(p_deny, '{}'::text[])) e;
|
|
2050
|
-
insert into ${includes} (tenant_id, scope, scope_id, role, include_role)
|
|
2051
|
-
select distinct p_tenant, p_scope, p_scope_id, p_role, e
|
|
2052
|
-
from unnest(coalesce(p_include, '{}'::text[])) e;`;
|
|
2053
|
-
const move = `${taken("p_to")} if ${roleName("p_to")} then
|
|
2054
|
-
${raiseSql(" ", "22023", `'permdock: ' || coalesce(p_to, 'null') || ' is not a custom role name'`, "declared-role")}
|
|
2055
|
-
end if;
|
|
2056
|
-
if exists (select 1 from ${perms} c where ${match} and c.role = p_to)
|
|
2057
|
-
or exists (select 1 from ${includes} c where ${match} and c.role = p_to) then
|
|
2058
|
-
${raiseSql(" ", "22023", `'permdock: ' || p_to || ' already has grants'`, "role-exists")}
|
|
2059
|
-
end if;
|
|
2060
|
-
update ${perms} c set role = p_to where ${match} and c.role = p_from;
|
|
2061
|
-
update ${includes} c set role = p_to where ${match} and c.role = p_from;`;
|
|
2062
|
-
const remove = ` delete from ${perms} c where ${match} and c.role = p_role;
|
|
2063
|
-
delete from ${includes} c where ${match} and c.role = p_role;`;
|
|
2064
|
-
const writeArgs = `${tenantType}, text, text, text, text[], text[], text[]`;
|
|
2065
|
-
const renameArgs = `${tenantType}, text, text, text, text`;
|
|
2066
|
-
const removeArgs = `${tenantType}, text, text, text`;
|
|
2067
|
-
const fn = (comment, name, params, args, body, member) => `-- ${comment}
|
|
2068
|
-
create or replace function ${qualified(ctx, name)}(${params})
|
|
2069
|
-
returns void
|
|
2070
|
-
language plpgsql
|
|
2071
|
-
volatile
|
|
2072
|
-
security definer
|
|
2073
|
-
set search_path = ''
|
|
2074
|
-
as $$
|
|
2075
|
-
${body}
|
|
2076
|
-
$$;
|
|
2077
|
-
${member ? `revoke execute on function ${qualified(ctx, name)}(${args}) from public, anon;
|
|
2078
|
-
grant execute on function ${qualified(ctx, name)}(${args}) to authenticated;` : `revoke execute on function ${qualified(ctx, name)}(${args}) from public, anon, authenticated;`}`;
|
|
2079
|
-
const writeParams = `p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text, p_allow text[], p_deny text[], p_include text[]`;
|
|
2080
|
-
const renameParams = `p_tenant ${tenantType}, p_scope text, p_scope_id text, p_from text, p_to text`;
|
|
2081
|
-
const removeParams = `p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text`;
|
|
2082
|
-
return `${caller.beyond}
|
|
2083
|
-
|
|
2084
|
-
-- 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
|
|
2085
|
-
create or replace function ${shape}(p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text)
|
|
2086
|
-
returns void
|
|
2087
|
-
language plpgsql
|
|
2088
|
-
stable
|
|
2089
|
-
set search_path = ''
|
|
2090
|
-
as $$
|
|
2091
|
-
begin
|
|
2092
|
-
if p_scope = 'global' then
|
|
2093
|
-
if p_tenant is not null or p_scope_id is not null then
|
|
2094
|
-
${raiseSql(" ", "22023", `'permdock: a platform custom role has no tenant or instance'`, "unknown-scope")}
|
|
2095
|
-
end if;
|
|
2096
|
-
elsif not (p_scope = any(${scopes})) then
|
|
2097
|
-
${raiseSql(" ", "22023", `'permdock: custom roles are held at a scope of a tenant or at global, not ' || coalesce(p_scope, 'null')`, "unknown-scope")}
|
|
2098
|
-
elsif p_tenant is null and p_scope_id is not null then
|
|
2099
|
-
${raiseSql(" ", "22023", `'permdock: a shared custom role has no instance'`, "unknown-scope")}
|
|
2100
|
-
end if;
|
|
2101
|
-
if ${roleName("p_role")} then
|
|
2102
|
-
${raiseSql(" ", "22023", `'permdock: ' || coalesce(p_role, 'null') || ' is not a custom role name'`, "declared-role")}
|
|
2103
|
-
end if;
|
|
2104
|
-
end;
|
|
2105
|
-
$$;
|
|
2106
|
-
revoke execute on function ${shape}(${tenantType}, text, text, text) from public, anon, authenticated;
|
|
2107
|
-
|
|
2108
|
-
${caller.guard}
|
|
2109
|
-
${hasCustomRoleChecksFor(ctx) ? `
|
|
2110
|
-
-- the same checks for a user the caller names: trusted SQL acting later for a stored user; no client role may execute them
|
|
2111
|
-
${callerFunctionsSql(ctx, custom, root, levelReach, true).beyond}
|
|
2112
|
-
|
|
2113
|
-
${callerFunctionsSql(ctx, custom, root, levelReach, true).guard}
|
|
2114
|
-
` : ""}
|
|
2115
|
-
-- 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" : ""}
|
|
2116
|
-
create or replace function ${problem}(p_scope text, p_entry text)
|
|
2117
|
-
returns text
|
|
2118
|
-
language plpgsql
|
|
2119
|
-
stable
|
|
2120
|
-
security definer
|
|
2121
|
-
set search_path = ''
|
|
2122
|
-
as $$
|
|
2123
|
-
declare
|
|
2124
|
-
v_key text := ${current(leveled ? "split_part(p_entry, '@', 1)" : "p_entry")};
|
|
2125
|
-
begin
|
|
2126
|
-
if p_entry is null or not (v_key = any(${known})) then
|
|
2127
|
-
return 'unknown-permission';
|
|
2128
|
-
end if;
|
|
2129
|
-
if not exists (
|
|
2130
|
-
select 1 from ${ceiling} c
|
|
2131
|
-
where c.scope = p_scope and c.effect = 'allow' and ${current("c.permission")} = v_key
|
|
2132
|
-
) then
|
|
2133
|
-
return 'outside-ceiling';
|
|
2134
|
-
end if;${leveled ? `
|
|
2135
|
-
if strpos(p_entry, '@') > 0 and not exists (
|
|
2136
|
-
select 1 from ${ceiling} c
|
|
2137
|
-
where c.scope = p_scope and c.effect = 'allow' and ${current("c.permission")} = v_key
|
|
2138
|
-
and split_part(c.grant_key, '@', 2) = split_part(p_entry, '@', 2)
|
|
2139
|
-
) then
|
|
2140
|
-
return 'unknown-level';
|
|
2141
|
-
end if;` : ""}
|
|
2142
|
-
return null;
|
|
2143
|
-
end;
|
|
2144
|
-
$$;
|
|
2145
|
-
revoke execute on function ${problem}(text, text) from public, anon, authenticated;
|
|
2146
|
-
|
|
2147
|
-
-- the entries of a definition: declared keys and levels inside the ceiling of the scope, and declared includes
|
|
2148
|
-
create or replace function ${entries}(p_scope text, p_allow text[], p_deny text[], p_include text[])
|
|
2149
|
-
returns void
|
|
2150
|
-
language plpgsql
|
|
2151
|
-
stable
|
|
2152
|
-
security definer
|
|
2153
|
-
set search_path = ''
|
|
2154
|
-
as $$
|
|
2155
|
-
declare
|
|
2156
|
-
v_entry text;
|
|
2157
|
-
v_key text;
|
|
2158
|
-
v_problem text;
|
|
2159
|
-
begin
|
|
2160
|
-
foreach v_entry in array coalesce(p_allow, '{}'::text[]) loop
|
|
2161
|
-
v_key := ${current(leveled ? "split_part(v_entry, '@', 1)" : "v_entry")};
|
|
2162
|
-
v_problem := ${problem}(p_scope, v_entry);
|
|
2163
|
-
if v_problem = 'unknown-permission' then
|
|
2164
|
-
${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' is not a declared permission'`, "unknown-permission")}
|
|
2165
|
-
end if;
|
|
2166
|
-
if v_problem = 'outside-ceiling' then
|
|
2167
|
-
${raiseSql(" ", "22023", `'permdock: ' || v_key || ' is outside the ceiling of ' || p_scope`, "outside-ceiling")}
|
|
2168
|
-
end if;${leveled ? `
|
|
2169
|
-
if v_problem = 'unknown-level' then
|
|
2170
|
-
${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' names a level the resource does not declare'`, "unknown-level")}
|
|
2171
|
-
end if;` : ""}
|
|
2172
|
-
end loop;
|
|
2173
|
-
foreach v_entry in array coalesce(p_deny, '{}'::text[]) loop
|
|
2174
|
-
if not (v_entry = any(${known})) then
|
|
2175
|
-
${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' is not a declared permission'`, "unknown-permission")}
|
|
2176
|
-
end if;
|
|
2177
|
-
end loop;
|
|
2178
|
-
foreach v_entry in array coalesce(p_include, '{}'::text[]) loop
|
|
2179
|
-
if not (v_entry = any(${sqlTextArray(custom.declared)})) then
|
|
2180
|
-
${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' is not a declared role'`, "unknown-role")}
|
|
2181
|
-
end if;
|
|
2182
|
-
end loop;
|
|
2183
|
-
select string_agg(distinct ${current("rp.permission")}, ', ') into v_key
|
|
2184
|
-
from ${rp} rp
|
|
2185
|
-
where rp.role = any(coalesce(p_include, '{}'::text[]))
|
|
2186
|
-
and rp.effect = 'allow'
|
|
2187
|
-
and not exists (
|
|
2188
|
-
select 1 from ${ceiling} c
|
|
2189
|
-
where c.scope = p_scope and c.effect = 'allow' and ${current("c.permission")} = ${current("rp.permission")}
|
|
2190
|
-
);
|
|
2191
|
-
if v_key is not null then
|
|
2192
|
-
${raiseSql(" ", "22023", `'permdock: an included role allows ' || v_key || ', outside the ceiling of ' || p_scope`, "outside-ceiling")}
|
|
2193
|
-
end if;
|
|
2194
|
-
end;
|
|
2195
|
-
$$;
|
|
2196
|
-
revoke execute on function ${entries}(text, text[], text[], text[]) from public, anon, authenticated;
|
|
2197
|
-
|
|
2198
|
-
${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
|
|
2199
|
-
v_beyond text;
|
|
2200
|
-
begin
|
|
2201
|
-
perform ${guard}(p_tenant, p_scope, p_scope_id, p_role);
|
|
2202
|
-
perform ${entries}(p_scope, p_allow, p_deny, p_include);
|
|
2203
|
-
select string_agg(b, ', ' order by b) into v_beyond
|
|
2204
|
-
from ${beyond}(p_tenant, p_scope, p_scope_id, p_allow, p_deny, p_include) b;
|
|
2205
|
-
if v_beyond is not null then
|
|
2206
|
-
${raiseSql(" ", "42501", `'permdock: ' || p_role || ' would allow ' || v_beyond || ', which the caller may not hand out'`, "not-assignable-by")}
|
|
2207
|
-
end if;
|
|
2208
|
-
${write}
|
|
2209
|
-
end;`, true)}
|
|
2210
|
-
|
|
2211
|
-
${fn("rename a custom role: move its grants and includes to the new name", CUSTOM_ROLES.rename, renameParams, renameArgs, `begin
|
|
2212
|
-
perform ${guard}(p_tenant, p_scope, p_scope_id, p_from);
|
|
2213
|
-
${move}
|
|
2214
|
-
end;`, true)}
|
|
2215
|
-
|
|
2216
|
-
${fn("delete a custom role: remove its grants and includes", CUSTOM_ROLES.remove, removeParams, removeArgs, `begin
|
|
2217
|
-
perform ${guard}(p_tenant, p_scope, p_scope_id, p_role);
|
|
2218
|
-
${remove}
|
|
2219
|
-
end;`, true)}
|
|
2220
|
-
|
|
2221
|
-
${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
|
|
2222
|
-
perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);
|
|
2223
|
-
perform ${entries}(p_scope, p_allow, p_deny, p_include);
|
|
2224
|
-
${write}
|
|
2225
|
-
end;`, false)}
|
|
2226
|
-
|
|
2227
|
-
${fn("rename a custom role for a trusted caller", CUSTOM_ROLES.trustedRename, renameParams, renameArgs, `begin
|
|
2228
|
-
perform ${shape}(p_tenant, p_scope, p_scope_id, p_from);
|
|
2229
|
-
${move}
|
|
2230
|
-
end;`, false)}
|
|
2231
|
-
|
|
2232
|
-
${fn("delete a custom role for a trusted caller", CUSTOM_ROLES.trustedRemove, removeParams, removeArgs, `begin
|
|
2233
|
-
perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);
|
|
2234
|
-
${remove}
|
|
2235
|
-
end;`, false)}`;
|
|
2236
|
-
}
|
|
2237
|
-
//#endregion
|
|
2238
|
-
//#region src/cli/rls/global-roles.ts
|
|
2239
|
-
/**
|
|
2240
|
-
* `permdock_replace_global_roles(p_user, p_roles)`: sets the global roles of
|
|
2241
|
-
* one user in `rls.roles` in one statement pair. It runs as the invoker, so the
|
|
2242
|
-
* table's policies and the `rls.assignments` trigger judge every row it deletes
|
|
2243
|
-
* or inserts.
|
|
2244
|
-
*/
|
|
2245
|
-
function globalRolesSql(ctx) {
|
|
2246
|
-
if (ctx.roles === void 0) return "";
|
|
2247
|
-
const source = globalRoleSource(ctx.roles, "public", "t", ctx.customRoles?.table);
|
|
2248
|
-
const table = quoteQualified(ctx.roles.table);
|
|
2249
|
-
const user = quoteIdent(source.user);
|
|
2250
|
-
const fn = qualified(ctx, GLOBAL_ROLES.replace);
|
|
2251
|
-
const type = ctx.dialect === "supabase" ? "uuid" : "text";
|
|
2252
|
-
const wanted = `select distinct r from unnest(coalesce(p_roles, '{}'::text[])) r where r is not null`;
|
|
2253
|
-
const through = source.through;
|
|
2254
|
-
let body;
|
|
2255
|
-
if (through === void 0) {
|
|
2256
|
-
const role = typeof ctx.roles.role === "string" ? ctx.roles.role : "role";
|
|
2257
|
-
const column = quoteIdent(role);
|
|
2258
|
-
body = ` delete from ${table} t
|
|
2259
|
-
where t.${user} = p_user
|
|
2260
|
-
and t.${column}::text <> all(coalesce(p_roles, '{}'::text[]));
|
|
2261
|
-
insert into ${table} (${user}, ${column})
|
|
2262
|
-
select p_user, w.r
|
|
2263
|
-
from (${wanted}) w(r)
|
|
2264
|
-
where not exists (
|
|
2265
|
-
select 1 from ${table} t where t.${user} = p_user and t.${column}::text = w.r
|
|
2266
|
-
);`;
|
|
2267
|
-
} else {
|
|
2268
|
-
const keys = quoteTable(through.table);
|
|
2269
|
-
const id = quoteIdent(through.id);
|
|
2270
|
-
const key = quoteIdent(through.key);
|
|
2271
|
-
const ref = quoteIdent(through.ref);
|
|
2272
|
-
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`}`;
|
|
2273
|
-
body = ` select string_agg(w.r, ', ' order by w.r) into v_unknown
|
|
2274
|
-
from (${wanted}) w(r)
|
|
2275
|
-
where not exists (select 1 from ${keys} k where k.${key}::text = w.r${global});
|
|
2276
|
-
if v_unknown is not null then
|
|
2277
|
-
raise exception using
|
|
2278
|
-
errcode = '22023',
|
|
2279
|
-
message = 'permdock: ' || v_unknown || ' is not a role',
|
|
2280
|
-
hint = 'unknown-role';
|
|
2281
|
-
end if;
|
|
2282
|
-
delete from ${table} t
|
|
2283
|
-
where t.${user} = p_user
|
|
2284
|
-
and not exists (
|
|
2285
|
-
select 1 from ${keys} k
|
|
2286
|
-
where k.${id} = t.${ref}
|
|
2287
|
-
and k.${key}::text = any(coalesce(p_roles, '{}'::text[]))${global}
|
|
2288
|
-
);
|
|
2289
|
-
insert into ${table} (${user}, ${ref})
|
|
2290
|
-
select p_user, k.${id}
|
|
2291
|
-
from ${keys} k
|
|
2292
|
-
where k.${key}::text in (${wanted})${global}
|
|
2293
|
-
and not exists (
|
|
2294
|
-
select 1 from ${table} t where t.${user} = p_user and t.${ref} = k.${id}
|
|
2295
|
-
);`;
|
|
2296
|
-
}
|
|
2297
|
-
const declare = through === void 0 ? "" : "declare\n v_unknown text;\n";
|
|
2298
|
-
const args = `${type}, text[]`;
|
|
2299
|
-
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
|
|
2300
|
-
create or replace function ${fn}(p_user ${type}, p_roles text[])
|
|
2301
|
-
returns void
|
|
2302
|
-
language plpgsql
|
|
2303
|
-
volatile
|
|
2304
|
-
set search_path = ''
|
|
2305
|
-
as $$
|
|
2306
|
-
${declare}begin
|
|
2307
|
-
${body}
|
|
2308
|
-
end;
|
|
2309
|
-
$$;
|
|
2310
|
-
revoke execute on function ${fn}(${args}) from public, anon;
|
|
2311
|
-
grant execute on function ${fn}(${args}) to authenticated;`;
|
|
2312
|
-
}
|
|
2313
|
-
//#endregion
|
|
2314
|
-
//#region src/cli/rls/helper-members.ts
|
|
2315
|
-
/**
|
|
2316
|
-
* The body of `member_<scope>_ids()`: instances of `scope` the subject holds a
|
|
2317
|
-
* live membership of, with any role. Not narrowed to the active tenant, and no
|
|
2318
|
-
* cascade: a membership of a child scope is not one of its parent.
|
|
2319
|
-
*/
|
|
2320
|
-
function memberBody(ctx, scope, type, roles) {
|
|
2321
|
-
if (ctx.authorize !== "database") return sqlBody(` select distinct (m ->> 'id')::${type}
|
|
2322
|
-
from jsonb_array_elements(
|
|
2323
|
-
case jsonb_typeof(${membershipClaim(ctx)}) when 'array' then ${membershipClaim(ctx)} else '[]'::jsonb end
|
|
2324
|
-
) m
|
|
2325
|
-
where ${signedIn(ctx)}
|
|
2326
|
-
and m ->> 'scope' = ${quoteLiteral(scope)}
|
|
2327
|
-
and m ->> 'id' is not null${keyTenantLine(ctx, scope, claimTenant(ctx, scope))}
|
|
2328
|
-
and jsonb_typeof(m -> 'roles') = 'array'
|
|
2329
|
-
and jsonb_array_length(m -> 'roles') > 0${roles === void 0 ? "" : `\n and (m -> 'roles') ?| ${roles}`}
|
|
2330
|
-
and case jsonb_typeof(m -> 'expires_at')
|
|
2331
|
-
when 'number' then (m ->> 'expires_at')::numeric > extract(epoch from now())
|
|
2332
|
-
else true
|
|
2333
|
-
end${[
|
|
2334
|
-
...claimKeptLines(ctx, " "),
|
|
2335
|
-
...userActive(ctx, " "),
|
|
2336
|
-
...instancesActive(ctx, scope, (name) => name === scope ? `m ->> 'id'` : `m -> 'within' ->> ${quoteLiteral(name)}`, " ")
|
|
2337
|
-
].map((line) => `\n${line}`).join("")}`);
|
|
2338
|
-
return memberRowsBody(ctx, scope, type, subjectIdSql(ctx), scopeSources(ctx, scope), true, roles);
|
|
2339
|
-
}
|
|
2340
|
-
/**
|
|
2341
|
-
* The membership rows of `user` for `scope`, from the sources or else the
|
|
2342
|
-
* mapped table, with the same expiry and suspension filters either way.
|
|
2343
|
-
*/
|
|
2344
|
-
function memberRowsBody(ctx, scope, type, user, sources, keyed = false, roles) {
|
|
2345
|
-
if (sources.length > 0) {
|
|
2346
|
-
const narrow = keyed ? keyTenantLine(ctx, scope, sourceIdOf(scope)(rootName(ctx))) : "";
|
|
2347
|
-
return sourcesBodyOf(` select distinct (ms.id)::${type}
|
|
2348
|
-
from (
|
|
2349
|
-
${sourceRows(sources)}
|
|
2350
|
-
) ms
|
|
2351
|
-
where ${signedIn(ctx, user)}
|
|
2352
|
-
and ms.scope = ${quoteLiteral(scope)}
|
|
2353
|
-
and jsonb_typeof(ms.roles) = 'array'
|
|
2354
|
-
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);
|
|
2355
|
-
}
|
|
2356
|
-
const mapped = scopeTable(ctx, scope);
|
|
2357
|
-
if (mapped === void 0) return sqlBody(` select null::${type} where false -- no ${scope} memberships table configured`);
|
|
2358
|
-
const { table, column, tenantColumn } = mapped;
|
|
2359
|
-
const role = memberRoleOf(table, "m", " ");
|
|
2360
|
-
const lines = [
|
|
2361
|
-
` select distinct ${memberColumn(column)}::${type}`,
|
|
2362
|
-
` from ${quoteQualified(table.table)} m${role.join}`,
|
|
2363
|
-
` where ${memberColumn(table.user)} = ${user}`,
|
|
2364
|
-
` and ${role.through === void 0 && !role.lateral ? memberColumn(role.column) : role.sql} is not null`
|
|
2365
|
-
];
|
|
2366
|
-
if (roles !== void 0) lines.push(` and (${role.through === void 0 && !role.lateral ? memberColumn(role.column) : role.sql})::text = any(${roles})`);
|
|
2367
|
-
const narrow = keyed ? keyTenantSql(ctx, tenantColumn === void 0 ? void 0 : memberColumn(tenantColumn)) : void 0;
|
|
2368
|
-
if (narrow !== void 0) lines.push(` and ${narrow}`);
|
|
2369
|
-
if (table.expiresAt !== void 0) {
|
|
2370
|
-
const expires = memberColumn(table.expiresAt);
|
|
2371
|
-
lines.push(` and (${expires} is null or ${expires} > now())`);
|
|
2372
|
-
}
|
|
2373
|
-
lines.push(...activeMembershipSql(ctx, disabledColumn(table), void 0).map((part) => ` and ${part}`), ...userActive(ctx, " ", user), ...instancesActive(ctx, scope, (name) => {
|
|
2374
|
-
const held = scopeColumn(table, ctx.scopes, name);
|
|
2375
|
-
return held === void 0 ? void 0 : memberColumn(held);
|
|
2376
|
-
}, " "));
|
|
2377
|
-
return sqlBody(lines.join("\n"));
|
|
2378
|
-
}
|
|
2379
|
-
function membershipClaim(ctx) {
|
|
2380
|
-
const raw = subjectClaimJsonSql(ctx, "memberships");
|
|
2381
|
-
return ctx.dialect === "supabase" ? `coalesce(${raw}, (select auth.jwt()) -> 'app_metadata' -> 'memberships')` : raw;
|
|
2382
|
-
}
|
|
2383
|
-
function memberFunction(ctx, scope, type, anonExecute) {
|
|
2384
|
-
const fn = qualified(ctx, memberIdsHelper(scope));
|
|
2385
|
-
const body = memberBody(ctx, scope, type);
|
|
2386
|
-
const keys = ctx.apiKeys;
|
|
2387
|
-
const keyed = keys === void 0 || scope !== rootName(ctx) ? body : {
|
|
2388
|
-
sql: `${body.sql}\n union\n${serviceKeyMemberSql(ctx, keys, scope, type)}`,
|
|
2389
|
-
vars: body.vars
|
|
2390
|
-
};
|
|
2391
|
-
const grants = anonExecute ? `revoke execute on function ${fn}() from public;
|
|
2392
|
-
grant execute on function ${fn}() to anon, authenticated;` : `revoke execute on function ${fn}() from public, anon;
|
|
2393
|
-
grant execute on function ${fn}() to authenticated;`;
|
|
2394
|
-
return `create or replace function ${fn}()
|
|
2395
|
-
returns setof ${type}
|
|
2396
|
-
${functionBody(keyed)}
|
|
2397
|
-
${grants}`;
|
|
2398
|
-
}
|
|
2399
|
-
/**
|
|
2400
|
-
* `member_<scope>_ids(p_roles text[])`: `member_<scope>_ids()` narrowed to
|
|
2401
|
-
* memberships holding one of `p_roles` by name, for `rls migrate`'s `role`
|
|
2402
|
-
* helpers. Generated only for a scope such a helper names.
|
|
2403
|
-
*/
|
|
2404
|
-
function memberRolesFunction(ctx, scope, type, anonExecute) {
|
|
2405
|
-
const fn = qualified(ctx, memberIdsHelper(scope));
|
|
2406
|
-
const body = memberBody(ctx, scope, type, "p_roles");
|
|
2407
|
-
const grants = anonExecute ? `revoke execute on function ${fn}(text[]) from public;
|
|
2408
|
-
grant execute on function ${fn}(text[]) to anon, authenticated;` : `revoke execute on function ${fn}(text[]) from public, anon;
|
|
2409
|
-
grant execute on function ${fn}(text[]) to authenticated;`;
|
|
2410
|
-
return `create or replace function ${fn}(p_roles text[])
|
|
2411
|
-
returns setof ${type}
|
|
2412
|
-
${functionBody(body)}
|
|
2413
|
-
${grants}`;
|
|
2414
|
-
}
|
|
2415
|
-
/**
|
|
2416
|
-
* `member_<scope>_ids_for(p_user uuid)`: `member_<scope>_ids()` for a user the
|
|
2417
|
-
* caller names, read from the membership sources (or the mapped table) in
|
|
2418
|
-
* either mode, so a token hook can call it before any claim exists. Naming the
|
|
2419
|
-
* user is why no client role may execute it; the hook's grants give
|
|
2420
|
-
* `supabase_auth_admin` execute.
|
|
2421
|
-
*/
|
|
2422
|
-
function memberForFunction(ctx, scope, type) {
|
|
2423
|
-
const fn = qualified(ctx, memberForHelper(scope));
|
|
2424
|
-
return `create or replace function ${fn}(p_user uuid)
|
|
2425
|
-
returns setof ${type}
|
|
2426
|
-
${functionBody(memberRowsBody(ctx, scope, type, "p_user", memberForSources(ctx, scope)))}
|
|
2427
|
-
revoke execute on function ${fn}(uuid) from public, anon, authenticated;`;
|
|
2428
|
-
}
|
|
2429
|
-
/**
|
|
2430
|
-
* `member_<scope>_ids_of(p_user uuid)`: `member_<scope>_ids_for(p_user)` for
|
|
2431
|
-
* the caller only. Any other `p_user` returns no rows, so a client role may
|
|
2432
|
-
* execute it without learning another user's memberships.
|
|
2433
|
-
*/
|
|
2434
|
-
function memberOfFunction(ctx, scope, type) {
|
|
2435
|
-
const fn = qualified(ctx, memberOfHelper(scope));
|
|
2436
|
-
return `create or replace function ${fn}(p_user uuid)
|
|
2437
|
-
returns setof ${type}
|
|
2438
|
-
${functionBody(sqlBody(` select m.id
|
|
2439
|
-
from ${qualified(ctx, memberForHelper(scope))}(p_user) as m(id)
|
|
2440
|
-
where p_user = ${subjectIdSql(ctx)}`))}
|
|
2441
|
-
revoke execute on function ${fn}(uuid) from public, anon;
|
|
2442
|
-
grant execute on function ${fn}(uuid) to authenticated;`;
|
|
2443
|
-
}
|
|
2444
|
-
//#endregion
|
|
2445
|
-
//#region src/cli/rls/memo-generation.ts
|
|
2446
|
-
const BUMP = "permdock_bump_memo_generation";
|
|
2447
|
-
const TRIGGER = "permdock_memo_generation";
|
|
2448
|
-
function add(targets, table, columns = []) {
|
|
2449
|
-
const key = qualifySqlTable(table);
|
|
2450
|
-
const existing = targets.get(key);
|
|
2451
|
-
if (existing === void 0) {
|
|
2452
|
-
targets.set(key, {
|
|
2453
|
-
table,
|
|
2454
|
-
columns: columns.length === 0 ? void 0 : new Set(columns)
|
|
2455
|
-
});
|
|
2456
|
-
return;
|
|
2457
|
-
}
|
|
2458
|
-
if (existing.columns === void 0 || columns.length === 0) {
|
|
2459
|
-
targets.set(key, {
|
|
2460
|
-
table: existing.table,
|
|
2461
|
-
columns: void 0
|
|
2462
|
-
});
|
|
2463
|
-
return;
|
|
2464
|
-
}
|
|
2465
|
-
for (const column of columns) existing.columns.add(column);
|
|
2466
|
-
}
|
|
2467
|
-
function suspensionTargets(targets, row) {
|
|
2468
|
-
if (row === void 0) return;
|
|
2469
|
-
const columns = [...row.disabledAt === void 0 ? [] : [row.disabledAt], ...row.status === void 0 ? [] : [row.status]];
|
|
2470
|
-
add(targets, row.table, columns);
|
|
2471
|
-
}
|
|
2472
|
-
const IDENT = String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)`;
|
|
2473
|
-
const READ = new RegExp(String.raw`(?<!\bdistinct\s+)(?<!\bextract\s*\([^()]*)\b(?:from|join)\s+(${IDENT})\.(${IDENT})(?![\w$]|\s*[.(])`, "gu");
|
|
2474
|
-
const SYSTEM = /* @__PURE__ */ new Set([
|
|
2475
|
-
"auth",
|
|
2476
|
-
"pg_catalog",
|
|
2477
|
-
"information_schema"
|
|
2478
|
-
]);
|
|
2479
|
-
function unquote(name) {
|
|
2480
|
-
return name.startsWith("\"") ? name.slice(1, -1).replaceAll("\"\"", "\"") : name;
|
|
2481
|
-
}
|
|
2482
|
-
function readTables(sql) {
|
|
2483
|
-
const out = /* @__PURE__ */ new Set();
|
|
2484
|
-
for (const [, schema = "", table = ""] of sql.matchAll(READ)) {
|
|
2485
|
-
const name = unquote(schema);
|
|
2486
|
-
if (!SYSTEM.has(name)) out.add(`${name}.${unquote(table)}`);
|
|
2487
|
-
}
|
|
2488
|
-
return [...out];
|
|
2489
|
-
}
|
|
2490
|
-
function memoTargets(ctx, reads) {
|
|
2491
|
-
const schema = helperSchema(ctx);
|
|
2492
|
-
const targets = /* @__PURE__ */ new Map();
|
|
2493
|
-
add(targets, `${schema}.role_permissions`);
|
|
2494
|
-
if (ctx.customRoles !== void 0) {
|
|
2495
|
-
add(targets, `${schema}.${CUSTOM_ROLES.permissions}`);
|
|
2496
|
-
add(targets, `${schema}.${CUSTOM_ROLES.includes}`);
|
|
2497
|
-
const roles = ctx.customRoles.table;
|
|
2498
|
-
if (roles !== void 0) add(targets, roles.table, [
|
|
2499
|
-
roles.key,
|
|
2500
|
-
...roles.tenant === void 0 ? [] : [roles.tenant],
|
|
2501
|
-
...roles.scope === void 0 ? [] : [roles.scope]
|
|
2502
|
-
]);
|
|
2503
|
-
}
|
|
2504
|
-
suspensionTargets(targets, ctx.suspension?.users);
|
|
2505
|
-
for (const row of Object.values(ctx.suspension?.scopes ?? {})) suspensionTargets(targets, row);
|
|
2506
|
-
for (const table of readTables(reads)) if (!targets.has(qualifySqlTable(table))) add(targets, table);
|
|
2507
|
-
if (ctx.seeds === "view") targets.delete(qualifySqlTable(`${schema}.role_permissions`));
|
|
2508
|
-
return targets;
|
|
2509
|
-
}
|
|
2510
|
-
function triggersSql(ctx, targets) {
|
|
2511
|
-
const trigger = qualified(ctx, TRIGGER);
|
|
2512
|
-
return [...targets].map(({ table, columns }) => {
|
|
2513
|
-
const target = quoteTable(qualifySqlTable(table));
|
|
2514
|
-
const update = columns === void 0 ? "update" : `update of ${[...columns].map((column) => quoteIdent(column)).join(", ")}`;
|
|
2515
|
-
return `drop trigger if exists ${quoteIdent(TRIGGER)} on ${target};
|
|
2516
|
-
create trigger ${quoteIdent(TRIGGER)}
|
|
2517
|
-
after insert or ${update} or delete on ${target}
|
|
2518
|
-
for each statement execute function ${trigger}();
|
|
2519
|
-
drop trigger if exists ${quoteIdent(`${TRIGGER}_truncate`)} on ${target};
|
|
2520
|
-
create trigger ${quoteIdent(`${TRIGGER}_truncate`)}
|
|
2521
|
-
after truncate on ${target}
|
|
2522
|
-
for each statement execute function ${trigger}();`;
|
|
2523
|
-
}).join("\n");
|
|
2524
|
-
}
|
|
2525
|
-
/**
|
|
2526
|
-
* The triggers that invalidate the memo when a write changes permitted ids
|
|
2527
|
-
* inside the statement: the permission map, a custom role's grants, a suspended
|
|
2528
|
-
* user or scope, and every table `reads` (the memoized helper bodies) selects
|
|
2529
|
-
* from, such as the membership sources and the global roles. The hook's version
|
|
2530
|
-
* triggers call the same bump.
|
|
2531
|
-
*/
|
|
2532
|
-
function memoGenerationSql(ctx, reads = "") {
|
|
2533
|
-
if (!memoizes(ctx)) return "";
|
|
2534
|
-
const bump = qualified(ctx, BUMP);
|
|
2535
|
-
const trigger = qualified(ctx, TRIGGER);
|
|
2536
|
-
return `-- a permission, custom-role, suspension or membership write changes permitted ids inside the statement
|
|
2537
|
-
create or replace function ${bump}()
|
|
2538
|
-
returns void
|
|
2539
|
-
language sql
|
|
2540
|
-
volatile
|
|
2541
|
-
security definer
|
|
2542
|
-
set search_path = ''
|
|
2543
|
-
as $$
|
|
2544
|
-
select set_config(
|
|
2545
|
-
'permdock.m.gen',
|
|
2546
|
-
(coalesce(nullif(current_setting('permdock.m.gen', true), ''), '0')::int + 1)::text,
|
|
2547
|
-
true
|
|
2548
|
-
)
|
|
2549
|
-
$$;
|
|
2550
|
-
revoke execute on function ${bump}() from public, anon, authenticated;
|
|
2551
|
-
|
|
2552
|
-
create or replace function ${trigger}()
|
|
2553
|
-
returns trigger
|
|
2554
|
-
language plpgsql
|
|
2555
|
-
volatile
|
|
2556
|
-
security definer
|
|
2557
|
-
set search_path = ''
|
|
2558
|
-
as $$
|
|
2559
|
-
begin
|
|
2560
|
-
perform ${bump}();
|
|
2561
|
-
return null;
|
|
2562
|
-
end;
|
|
2563
|
-
$$;
|
|
2564
|
-
revoke execute on function ${trigger}() from public, anon, authenticated;
|
|
2565
|
-
${triggersSql(ctx, memoTargets(ctx, reads).values())}`;
|
|
2566
|
-
}
|
|
2567
|
-
function memoReadTriggersSql(ctx, reads, covered) {
|
|
2568
|
-
const done = memoTargets(ctx, covered);
|
|
2569
|
-
const targets = /* @__PURE__ */ new Map();
|
|
2570
|
-
for (const table of readTables(reads)) if (!done.has(qualifySqlTable(table))) add(targets, table);
|
|
2571
|
-
return targets.size === 0 ? "" : triggersSql(ctx, targets.values());
|
|
2572
|
-
}
|
|
2573
|
-
//#endregion
|
|
2574
|
-
//#region src/cli/rls/token-scopes.ts
|
|
2575
|
-
const TOKEN_SCOPE_ALLOWS = "permdock_token_scope_allows";
|
|
2576
|
-
const TOKEN_SCOPE_MAP = "permdock_token_scope_map";
|
|
2577
|
-
/**
|
|
2578
|
-
* `rls.tokenScopes` as the SQL generator needs it, or `undefined` when it is
|
|
2579
|
-
* off.
|
|
2580
|
-
*/
|
|
2581
|
-
function tokenScopesPlan(setting, policy) {
|
|
2582
|
-
if (setting !== true) return;
|
|
2583
|
-
const permissions = listPermissions(policy.permissions).map((leaf) => ({
|
|
2584
|
-
key: leaf.key,
|
|
2585
|
-
scope: leaf.scope,
|
|
2586
|
-
renamedFrom: formerKeys(leaf)
|
|
2587
|
-
}));
|
|
2588
|
-
return { scopes: delegatedScopeMap(permissions, policy.oauthScopes) };
|
|
2589
|
-
}
|
|
2590
|
-
function tokenScopeAllowsCall(ctx, grant) {
|
|
2591
|
-
return `${qualified(ctx, TOKEN_SCOPE_ALLOWS)}(${grant})`;
|
|
2592
|
-
}
|
|
2593
|
-
/**
|
|
2594
|
-
* The token's scopes as rows of `s(scope)`: a space-separated string or,
|
|
2595
|
-
* outside `guc`, a JSON array.
|
|
2596
|
-
*/
|
|
2597
|
-
function tokenScopeRows(ctx) {
|
|
2598
|
-
if (ctx.dialect === "guc") return `regexp_split_to_table(btrim(coalesce(${subjectClaimSql(ctx, "scope")}, '')), '\\s+') s(scope)`;
|
|
2599
|
-
const scope = subjectClaimJsonSql(ctx, "scope");
|
|
2600
|
-
return `unnest(case jsonb_typeof(${scope})
|
|
2601
|
-
when 'string' then regexp_split_to_array(btrim(${scope} #>> '{}'), '\\s+')
|
|
2602
|
-
when 'array' then array(select jsonb_array_elements_text(${scope}))
|
|
2603
|
-
else '{}'::text[]
|
|
2604
|
-
end) s(scope)`;
|
|
2605
|
-
}
|
|
2606
|
-
/**
|
|
2607
|
-
* `permdock_token_scope_allows(p_grant)`: a delegated token (a `client_id`, or
|
|
2608
|
-
* an `act` that is not a support or impersonation session) reaches a grant key
|
|
2609
|
-
* only when one of its scopes maps to the key's permission. better-supabase's
|
|
2610
|
-
* `cap_allows` reads the same tokens the same way.
|
|
2611
|
-
*/
|
|
2612
|
-
function tokenScopeAllowsSql(ctx, plan, anonExecute) {
|
|
2613
|
-
const fn = qualified(ctx, TOKEN_SCOPE_ALLOWS);
|
|
2614
|
-
const map = qualified(ctx, TOKEN_SCOPE_MAP);
|
|
2615
|
-
const act = subjectClaimJsonSql(ctx, "act");
|
|
2616
|
-
const grants = anonExecute ? `revoke execute on function ${fn}(text) from public;
|
|
2617
|
-
grant execute on function ${fn}(text) to anon, authenticated;` : `revoke execute on function ${fn}(text) from public, anon;
|
|
2618
|
-
grant execute on function ${fn}(text) to authenticated;`;
|
|
2619
|
-
return `create or replace function ${map}()
|
|
2620
|
-
returns jsonb
|
|
2621
|
-
language sql
|
|
2622
|
-
immutable
|
|
2623
|
-
set search_path = ''
|
|
2624
|
-
as $$
|
|
2625
|
-
select ${quoteLiteral(JSON.stringify(plan.scopes))}::jsonb
|
|
2626
|
-
$$;
|
|
2627
|
-
revoke execute on function ${map}() from public, anon, authenticated;
|
|
2628
|
-
|
|
2629
|
-
-- 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
|
|
2630
|
-
create or replace function ${fn}(p_grant text)
|
|
2631
|
-
returns boolean
|
|
2632
|
-
language sql
|
|
2633
|
-
stable
|
|
2634
|
-
security definer
|
|
2635
|
-
set search_path = ''
|
|
2636
|
-
as $$
|
|
2637
|
-
select case
|
|
2638
|
-
when coalesce(${subjectClaimSql(ctx, "client_id")}, '') = ''
|
|
2639
|
-
and (${act} is null
|
|
2640
|
-
or ${act} = 'null'::jsonb
|
|
2641
|
-
or (jsonb_typeof(${act}) = 'object'
|
|
2642
|
-
and ${act} ->> 'kind' in ('support', 'impersonation'))) then true
|
|
2643
|
-
when exists (
|
|
2644
|
-
select 1 from ${qualified(ctx, "role_permissions")} rp
|
|
2645
|
-
where rp.grant_key = p_grant and rp.effect = 'deny'
|
|
2646
|
-
) then true
|
|
2647
|
-
else exists (
|
|
2648
|
-
select 1
|
|
2649
|
-
from ${tokenScopeRows(ctx)}
|
|
2650
|
-
where s.scope <> ''
|
|
2651
|
-
and coalesce(${map}() -> s.scope, '[]'::jsonb)
|
|
2652
|
-
? split_part(split_part(p_grant, '#', 1), '@', 1)
|
|
2653
|
-
)
|
|
2654
|
-
end
|
|
2655
|
-
$$;
|
|
2656
|
-
${grants}`;
|
|
2657
|
-
}
|
|
2658
|
-
//#endregion
|
|
2659
|
-
//#region src/cli/rls/helpers.ts
|
|
2660
|
-
/**
|
|
2661
|
-
* The policy-side call for a grant key. Every form is uncorrelated, so Postgres
|
|
2662
|
-
* runs the helper once per statement (an InitPlan, or a hashed SubPlan for
|
|
2663
|
-
* `in`), never once per row.
|
|
2664
|
-
*/
|
|
2665
|
-
function accessSql(ctx, scope, grantKey, column, helper) {
|
|
2666
|
-
const key = quoteLiteral(grantKey);
|
|
2667
|
-
if (scope === "global") return `(select ${qualified(ctx, HELPERS.has)}(${key}))`;
|
|
2668
|
-
if (column === void 0) throw configError(`PermDock CLI: ${scope}-scoped grant needs definePolicy({ scopes.${scope} })`);
|
|
2669
|
-
return `${quoteIdent(column)} in (select ${qualified(ctx, helper ?? permittedIdsHelper(scope))}(${key}))`;
|
|
2670
|
-
}
|
|
2671
|
-
/**
|
|
2672
|
-
* `permitted_<parent>_ids(p_grant)` for each \`rls.tables\` \`via\`: the parent
|
|
2673
|
-
* rows whose scope instance the grant reaches. \`security definer\`, so the
|
|
2674
|
-
* caller needs no read on the parent, and called uncorrelated like
|
|
2675
|
-
* \`permitted_<scope>_ids\`.
|
|
2676
|
-
*/
|
|
2677
|
-
function viaHelpersSql(ctx, anonExecute) {
|
|
2678
|
-
const done = /* @__PURE__ */ new Set();
|
|
2679
|
-
const chunks = [];
|
|
2680
|
-
for (const via of Object.values(ctx.vias ?? {})) {
|
|
2681
|
-
if (done.has(via.helper)) continue;
|
|
2682
|
-
done.add(via.helper);
|
|
2683
|
-
chunks.push(`-- rows of ${via.table} whose ${via.column} is a ${via.scope} the grant reaches
|
|
2684
|
-
${helperFunction(ctx, via.helper, `setof ${via.type}`, sqlBody(` select p.${quoteIdent(via.id)}
|
|
2685
|
-
from ${quoteQualified(via.table)} p
|
|
2686
|
-
where p.${quoteIdent(via.column)} in (select ${qualified(ctx, permittedIdsHelper(via.scope))}(p_grant))`), anonExecute)}`);
|
|
2687
|
-
}
|
|
2688
|
-
return chunks;
|
|
2689
|
-
}
|
|
2690
|
-
function userIdSql(ctx, anonExecute) {
|
|
2691
|
-
const fn = userIdHelperSql(ctx);
|
|
2692
|
-
return `-- the caller's user id: the sub of request.jwt.claims, or null when it is empty or absent
|
|
2693
|
-
create or replace function ${fn}()
|
|
2694
|
-
returns uuid
|
|
2695
|
-
language sql
|
|
2696
|
-
stable
|
|
2697
|
-
set search_path = ''
|
|
2698
|
-
as $$
|
|
2699
|
-
select nullif(
|
|
2700
|
-
nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub',
|
|
2701
|
-
''
|
|
2702
|
-
)::uuid
|
|
2703
|
-
$$;
|
|
2704
|
-
${anonExecute ? `revoke execute on function ${fn}() from public;
|
|
2705
|
-
grant execute on function ${fn}() to anon, authenticated;` : `revoke execute on function ${fn}() from public, anon;
|
|
2706
|
-
grant execute on function ${fn}() to authenticated;`}`;
|
|
2707
|
-
}
|
|
2708
|
-
function tokenCurrentSql(ctx, anonExecute) {
|
|
2709
|
-
const fn = qualified(ctx, HELPERS.tokenCurrent);
|
|
2710
|
-
const version = qualified(ctx, AUTHZ_VERSION_TABLE);
|
|
2711
|
-
const grants = anonExecute ? `revoke execute on function ${fn}() from public;
|
|
2712
|
-
grant execute on function ${fn}() to anon, authenticated;` : `revoke execute on function ${fn}() from public, anon;
|
|
2713
|
-
grant execute on function ${fn}() to authenticated;`;
|
|
2714
|
-
return `create or replace function ${fn}()
|
|
2715
|
-
returns boolean
|
|
2716
|
-
language plpgsql
|
|
2717
|
-
stable
|
|
2718
|
-
security definer
|
|
2719
|
-
set search_path = ''
|
|
2720
|
-
as $$
|
|
2721
|
-
begin
|
|
2722
|
-
return coalesce((
|
|
2723
|
-
select to_jsonb(v.version) = ((select auth.jwt()) -> 'authz_ver')
|
|
2724
|
-
and coalesce((select auth.jwt()) -> 'memberships_truncated', 'false'::jsonb) <> 'true'::jsonb
|
|
2725
|
-
and jsonb_typeof((select auth.jwt()) -> 'memberships') = 'array'
|
|
2726
|
-
from ${version} v
|
|
2727
|
-
where v.user_id = ${subjectIdSql(ctx)}
|
|
2728
|
-
), false);
|
|
2729
|
-
end;
|
|
2730
|
-
$$;
|
|
2731
|
-
${grants}`;
|
|
2732
|
-
}
|
|
2733
|
-
function helperFunction(ctx, name, returns, body, anonExecute) {
|
|
2734
|
-
const fn = qualified(ctx, name);
|
|
2735
|
-
const grants = anonExecute ? `revoke execute on function ${fn}(text) from public;
|
|
2736
|
-
grant execute on function ${fn}(text) to anon, authenticated;` : `revoke execute on function ${fn}(text) from public, anon;
|
|
2737
|
-
grant execute on function ${fn}(text) to authenticated;`;
|
|
2738
|
-
return `create or replace function ${fn}(p_grant text)
|
|
2739
|
-
returns ${returns}
|
|
2740
|
-
${functionBody(body, !memoizes(ctx))}
|
|
2741
|
-
${grants}`;
|
|
2742
|
-
}
|
|
2743
|
-
/**
|
|
2744
|
-
* `permdock_has_for(p_user, p_grant)` and one
|
|
2745
|
-
* `permitted_<scope>_ids_for(p_user, p_grant)` per scope in `database` mode:
|
|
2746
|
-
* the bodies of `permdock_has` and `permitted_<scope>_ids` with `p_user` for
|
|
2747
|
-
* the signed-in user and no tenant-claim narrowing, since a named user has no
|
|
2748
|
-
* token. For trusted SQL that acts for a stored user (jobs, triggers, approvals
|
|
2749
|
-
* resolved later). Naming the user is why no client role may execute them:
|
|
2750
|
-
* `security definer` callers run them as their owner, and a backend role needs
|
|
2751
|
-
* its own grant.
|
|
2752
|
-
*/
|
|
2753
|
-
function forUserSql(ctx) {
|
|
2754
|
-
if (ctx.authorize !== "database") return "";
|
|
2755
|
-
const forUser = forUserContext(ctx);
|
|
2756
|
-
const type = ctx.dialect === "supabase" ? "uuid" : "text";
|
|
2757
|
-
const fn = (name, returns, body) => {
|
|
2758
|
-
const qualifiedName = qualified(ctx, name);
|
|
2759
|
-
return `create or replace function ${qualifiedName}(p_user ${type}, p_grant text)
|
|
2760
|
-
returns ${returns}
|
|
2761
|
-
${functionBody(body, !memoizes(ctx))}
|
|
2762
|
-
revoke execute on function ${qualifiedName}(${type}, text) from public, anon, authenticated;`;
|
|
2763
|
-
};
|
|
2764
|
-
return [`-- the helpers for a user the caller names: trusted SQL acting for a stored user; no client role may execute them
|
|
2765
|
-
${fn(HELPERS.hasFor, "boolean", sqlBody(hasBody(forUser)))}`, ...ctx.scopes.map((scope) => {
|
|
2766
|
-
const scopeType = scopeTypeOf(ctx, scope.name);
|
|
2767
|
-
return fn(permittedForHelper(scope.name), `setof ${scopeType}`, scopedBody(forUser, scope.name, scopeType));
|
|
2768
|
-
})].join("\n\n");
|
|
2769
|
-
}
|
|
2770
|
-
function userIdType(ctx) {
|
|
2771
|
-
return ctx.dialect === "supabase" ? "uuid not null references auth.users on delete cascade" : "text not null";
|
|
2772
|
-
}
|
|
2773
|
-
/**
|
|
2774
|
-
* The `role_permissions` rows the policy compiles to: an upsert and a delete of
|
|
2775
|
-
* every other row. Data, not schema, so `supabase db diff` drops it from a
|
|
2776
|
-
* declarative schema; `--split ...,seeds` writes it as its own migration.
|
|
2777
|
-
*/
|
|
2778
|
-
function seedSql(ctx, rows) {
|
|
2779
|
-
const table = qualified(ctx, "role_permissions");
|
|
2780
|
-
if (rows.length === 0) return `delete from ${table};`;
|
|
2781
|
-
return `insert into ${table} (role, permission, grant_key, scope, effect) values
|
|
2782
|
-
${rows.map((row) => ` (${[
|
|
2783
|
-
row.role,
|
|
2784
|
-
row.permission,
|
|
2785
|
-
row.grantKey,
|
|
2786
|
-
row.scope,
|
|
2787
|
-
row.effect
|
|
2788
|
-
].map(quoteLiteral).join(", ")})`).join(",\n")}
|
|
2789
|
-
on conflict (role, grant_key, scope) do update
|
|
2790
|
-
set permission = excluded.permission, effect = excluded.effect;
|
|
2791
|
-
delete from ${table}
|
|
2792
|
-
where (role, grant_key, scope) not in (values
|
|
2793
|
-
${rows.map((row) => ` (${[
|
|
2794
|
-
row.role,
|
|
2795
|
-
row.grantKey,
|
|
2796
|
-
row.scope
|
|
2797
|
-
].map(quoteLiteral).join(", ")})`).join(",\n")}
|
|
2798
|
-
);`;
|
|
2799
|
-
}
|
|
2800
|
-
/**
|
|
2801
|
-
* `role_permissions` as a view over the compiled rows (`rls.seeds: 'view'`).
|
|
2802
|
-
* `security_invoker` makes the view read as its caller, so it adds no
|
|
2803
|
-
* privilege; the table's revoke applies to the view the same way.
|
|
2804
|
-
*/
|
|
2805
|
-
function seedViewSql(ctx, rows) {
|
|
2806
|
-
const view = qualified(ctx, "role_permissions");
|
|
2807
|
-
const columns = "role, permission, grant_key, scope, effect";
|
|
2808
|
-
return `-- rls.seeds: 'view': role_permissions is a view, so the rows travel with the schema
|
|
2809
|
-
create or replace view ${view} (${columns}) with (security_invoker = true) as
|
|
2810
|
-
${rows.length === 0 ? `select null::text, null::text, null::text, null::text, null::text where false` : `select * from (values\n${rows.map((row) => ` (${[
|
|
2811
|
-
row.role,
|
|
2812
|
-
row.permission,
|
|
2813
|
-
row.grantKey,
|
|
2814
|
-
row.scope,
|
|
2815
|
-
row.effect
|
|
2816
|
-
].map(quoteLiteral).join(", ")})`).join(",\n")}\n) as v(${columns})`};
|
|
2817
|
-
revoke all on table ${view} from anon, authenticated, public;`;
|
|
2818
|
-
}
|
|
2819
|
-
/**
|
|
2820
|
-
* `<schema>.seed()`: the same upsert and delete as `seedSql`, for a declarative
|
|
2821
|
-
* schema that carries no rows.
|
|
2822
|
-
*/
|
|
2823
|
-
function seedFunctionSql(ctx, rows) {
|
|
2824
|
-
const fn = qualified(ctx, "seed");
|
|
2825
|
-
return `-- rls.seeds: 'function': the role_permissions rows are data, so a declarative diff leaves them out; run select ${fn}(); after each deploy
|
|
2826
|
-
create or replace function ${fn}()
|
|
2827
|
-
returns void
|
|
2828
|
-
language sql
|
|
2829
|
-
volatile
|
|
2830
|
-
security definer
|
|
2831
|
-
set search_path = ''
|
|
2832
|
-
as $permdock$
|
|
2833
|
-
${seedSql(ctx, rows)}
|
|
2834
|
-
$permdock$;
|
|
2835
|
-
revoke execute on function ${fn}() from public, anon, authenticated;`;
|
|
2836
|
-
}
|
|
2837
|
-
/**
|
|
2838
|
-
* `role_permissions`, its seeds, and the three `security definer` helpers with
|
|
2839
|
-
* `search_path = ''`. `execute` goes to `authenticated` only.
|
|
2840
|
-
*/
|
|
2841
|
-
function helpersSql(ctx, rows, options) {
|
|
2842
|
-
const schema = helperSchema(ctx);
|
|
2843
|
-
const s = quoteIdent(schema);
|
|
2844
|
-
const rp = qualified(ctx, "role_permissions");
|
|
2845
|
-
const chunks = [`-- permdock helpers (${ctx.authorize === "database" ? "database: reads the membership and user_roles tables" : "jwt: reads the role and memberships claims"})
|
|
2846
|
-
-- policies call them uncorrelated, so Postgres evaluates each once per statement`];
|
|
2847
|
-
if (schema !== "public") {
|
|
2848
|
-
const anonUsage = options.anonExecute === true || ctx.capabilities === true;
|
|
2849
|
-
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"};`);
|
|
2850
|
-
}
|
|
2851
|
-
if (ctx.dialect === "supabase") chunks.push(userIdSql(ctx, options.anonExecute === true));
|
|
2852
|
-
if (ctx.claimsFirst === true) chunks.push(tokenCurrentSql(ctx, options.anonExecute === true));
|
|
2853
|
-
if (ctx.seeds === "view") chunks.push(seedViewSql(ctx, rows));
|
|
2854
|
-
else chunks.push(`create table if not exists ${rp} (
|
|
2855
|
-
role text not null,
|
|
2856
|
-
permission text not null,
|
|
2857
|
-
grant_key text not null,
|
|
2858
|
-
scope text not null check (scope ~ '^[a-z][a-z0-9_]*$'),
|
|
2859
|
-
effect text not null default 'allow' check (effect in ('allow', 'deny')),
|
|
2860
|
-
primary key (role, grant_key, scope)
|
|
2861
|
-
);
|
|
2862
|
-
alter table ${rp} enable row level security;
|
|
2863
|
-
revoke all on table ${rp} from anon, authenticated, public;`);
|
|
2864
|
-
if (ctx.seeds === "function") chunks.push(seedFunctionSql(ctx, rows));
|
|
2865
|
-
else if (options.withoutSeeds !== true && ctx.seeds !== "view") chunks.push(seedSql(ctx, rows));
|
|
2866
|
-
if (ctx.authorize === "database" && options.userRoles && ctx.roles === void 0) {
|
|
2867
|
-
const ur = qualified(ctx, "user_roles");
|
|
2868
|
-
chunks.push(`create table if not exists ${ur} (
|
|
2869
|
-
user_id ${userIdType(ctx)},
|
|
2870
|
-
role text not null,
|
|
2871
|
-
primary key (user_id, role)
|
|
2872
|
-
);
|
|
2873
|
-
alter table ${ur} enable row level security;
|
|
2874
|
-
revoke all on table ${ur} from anon, authenticated, public;`);
|
|
2875
|
-
}
|
|
2876
|
-
const custom = customRolesSql(ctx);
|
|
2877
|
-
if (custom !== "") chunks.push(custom);
|
|
2878
|
-
const memoGeneration = memoGenerationSql(ctx, memoReadsSql(ctx));
|
|
2879
|
-
if (memoGeneration !== "") chunks.push(memoGeneration);
|
|
2880
|
-
const anon = options.anonExecute === true;
|
|
2881
|
-
const keys = ctx.apiKeys;
|
|
2882
|
-
if (keys !== void 0) chunks.push(apiKeyAllowsSql(ctx, keys, anon));
|
|
2883
|
-
if (ctx.tokenScopes !== void 0) chunks.push(tokenScopeAllowsSql(ctx, ctx.tokenScopes, anon));
|
|
2884
|
-
const bodies = grantBodies(ctx);
|
|
2885
|
-
chunks.push(helperFunction(ctx, HELPERS.has, "boolean", bodies.has, anon));
|
|
2886
|
-
const capabilities = capabilitiesSql(ctx);
|
|
2887
|
-
if (capabilities !== "") chunks.push(capabilities);
|
|
2888
|
-
for (const scope of ctx.scopes) {
|
|
2889
|
-
const type = scopeTypeOf(ctx, scope.name);
|
|
2890
|
-
chunks.push(helperFunction(ctx, permittedIdsHelper(scope.name), `setof ${type}`, bodies.ids(scope.name), anon));
|
|
2891
|
-
chunks.push(memberFunction(ctx, scope.name, type, anon));
|
|
2892
|
-
if (ctx.roleMemberScopes?.includes(scope.name) === true) chunks.push(memberRolesFunction(ctx, scope.name, type, anon));
|
|
2893
|
-
if (hasMemberFor(ctx, scope.name)) chunks.push(memberForFunction(ctx, scope.name, type));
|
|
2894
|
-
if (hasMemberOf(ctx, scope.name)) chunks.push(memberOfFunction(ctx, scope.name, type));
|
|
2895
|
-
}
|
|
2896
|
-
chunks.push(...viaHelpersSql(ctx, anon));
|
|
2897
|
-
const forUser = forUserSql(ctx);
|
|
2898
|
-
if (forUser !== "") chunks.push(forUser);
|
|
2899
|
-
const writes = customRoleWritesSql(ctx, options.levelReach ?? []);
|
|
2900
|
-
if (writes !== "") {
|
|
2901
|
-
chunks.push(writes);
|
|
2902
|
-
const cascade = customRoleCascadeSql(ctx);
|
|
2903
|
-
if (cascade !== "") chunks.push(cascade);
|
|
2904
|
-
const sync = ctx.customRoles?.sync;
|
|
2905
|
-
if (sync !== void 0) chunks.push(sync);
|
|
2906
|
-
const byId = customRoleByIdSql(ctx, options.trustedReaders);
|
|
2907
|
-
if (byId !== "") chunks.push(byId);
|
|
2908
|
-
const nameGuard = customRoleNameGuardSql(ctx);
|
|
2909
|
-
if (nameGuard !== "") chunks.push(nameGuard);
|
|
2910
|
-
}
|
|
2911
|
-
const globalRoles = globalRolesSql(ctx);
|
|
2912
|
-
if (globalRoles !== "") chunks.push(globalRoles);
|
|
2913
|
-
chunks.push(roleReadersSql(ctx, options.permissions, options.trustedReaders));
|
|
2914
|
-
return `${chunks.join("\n\n")}\n`;
|
|
2915
|
-
}
|
|
2916
|
-
function memoBody(ctx, scope, type, body) {
|
|
2917
|
-
if (!memoizes(ctx)) return body;
|
|
2918
|
-
return {
|
|
2919
|
-
...body,
|
|
2920
|
-
memo: {
|
|
2921
|
-
type,
|
|
2922
|
-
scope,
|
|
2923
|
-
user: subjectIdSql(ctx),
|
|
2924
|
-
...ctx.memo === void 0 ? {} : { api: ctx.memo }
|
|
2925
|
-
}
|
|
2926
|
-
};
|
|
2927
|
-
}
|
|
2928
|
-
function memoReadsSql(ctx) {
|
|
2929
|
-
const bodies = grantBodies(ctx);
|
|
2930
|
-
return [bodies.has.sql, ...ctx.scopes.map((scope) => bodies.ids(scope.name).sql)].join("\n");
|
|
2931
|
-
}
|
|
2932
|
-
function grantBodies(ctx) {
|
|
2933
|
-
const keys = ctx.apiKeys;
|
|
2934
|
-
const scoped = ctx.tokenScopes !== void 0;
|
|
2935
|
-
const set = ctx.grantSet === true;
|
|
2936
|
-
const ceiling = (grant) => {
|
|
2937
|
-
const calls = [...keys === void 0 ? [] : [apiKeyAllowsCall(ctx, grant)], ...scoped ? [tokenScopeAllowsCall(ctx, grant)] : []];
|
|
2938
|
-
return calls.length === 0 ? void 0 : calls.join(" and ");
|
|
2939
|
-
};
|
|
2940
|
-
const allows = ceiling(set ? "ids.grant_key" : "p_grant");
|
|
2941
|
-
const keyTenant = keys === void 0 ? "" : ` and ${keyTenantSql(ctx, void 0) ?? "true"}`;
|
|
2942
|
-
const hasAllows = ceiling(set ? "g.grant_key" : "p_grant");
|
|
2943
|
-
return {
|
|
2944
|
-
has: memoBody(ctx, "global", "boolean", sqlBody(hasAllows === void 0 ? hasBody(ctx) : set ? ` select g.grant_key
|
|
2945
|
-
from (
|
|
2946
|
-
${hasBody(ctx)}
|
|
2947
|
-
) g(grant_key)
|
|
2948
|
-
where ${hasAllows}${keyTenant}` : ceilingHasSql(hasBody(ctx), `${hasAllows}${keyTenant}`))),
|
|
2949
|
-
ids: (scope) => {
|
|
2950
|
-
const type = scopeTypeOf(ctx, scope);
|
|
2951
|
-
const body = scopedBody(ctx, scope, type);
|
|
2952
|
-
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;
|
|
2953
|
-
return memoBody(ctx, scope, type, allows === void 0 ? {
|
|
2954
|
-
sql,
|
|
2955
|
-
vars: body.vars
|
|
2956
|
-
} : {
|
|
2957
|
-
sql: set ? ` select ids.id, ids.grant_key
|
|
2958
|
-
from (
|
|
2959
|
-
${sql}
|
|
2960
|
-
) ids(id, grant_key)
|
|
2961
|
-
where ${allows}` : ceilingIdsSql(sql, allows),
|
|
2962
|
-
vars: body.vars
|
|
2963
|
-
});
|
|
2964
|
-
}
|
|
2965
|
-
};
|
|
2966
|
-
}
|
|
2967
|
-
function forUserContext(ctx) {
|
|
2968
|
-
const { apiKeys: _apiKeys, tokenScopes: _tokenScopes, claimsFirst: _claimsFirst, ...unkeyed } = ctx;
|
|
2969
|
-
return {
|
|
2970
|
-
...unkeyed,
|
|
2971
|
-
subjectId: "p_user",
|
|
2972
|
-
tenants: "all"
|
|
2973
|
-
};
|
|
2974
|
-
}
|
|
2975
|
-
//#endregion
|
|
2976
|
-
//#region src/cli/rls/permission-keys.ts
|
|
2977
|
-
/**
|
|
2978
|
-
* The helpers that take a permission key instead of a grant key. Names are part
|
|
2979
|
-
* of the SQL contract.
|
|
2980
|
-
*/
|
|
2981
|
-
const PERMISSION_HELPERS = {
|
|
2982
|
-
grantKeys: "grant_keys",
|
|
2983
|
-
has: "permdock_has_permission",
|
|
2984
|
-
hasFor: "permdock_has_permission_for"
|
|
2985
|
-
};
|
|
2986
|
-
/**
|
|
2987
|
-
* `permitted_<scope>_permission_keys(p_id)`: every permission key the subject
|
|
2988
|
-
* holds on one instance.
|
|
2989
|
-
*/
|
|
2990
|
-
function permissionKeysHelper(scope) {
|
|
2991
|
-
permittedIdsHelper(scope);
|
|
2992
|
-
return `permitted_${scope}_permission_keys`;
|
|
2993
|
-
}
|
|
2994
|
-
/**
|
|
2995
|
-
* `permitted_<scope>_permission_keys_for(p_user, p_id)`, written in `database`
|
|
2996
|
-
* mode.
|
|
2997
|
-
*/
|
|
2998
|
-
function permissionKeysForHelper(scope) {
|
|
2999
|
-
return `${permissionKeysHelper(scope)}_for`;
|
|
3000
|
-
}
|
|
3001
|
-
/** `permitted_<scope>_ids_by_permission(p_permission)`. */
|
|
3002
|
-
function permittedByPermissionHelper(scope) {
|
|
3003
|
-
return `${permittedIdsHelper(scope)}_by_permission`;
|
|
3004
|
-
}
|
|
3005
|
-
/**
|
|
3006
|
-
* A grant's `requires` as SQL: the subject holds `key` globally, or on the
|
|
3007
|
-
* row's instance of a scope that partitions it, through the helpers by
|
|
3008
|
-
* permission key, as `requirementCondition` does in process.
|
|
3009
|
-
*/
|
|
3010
|
-
function requiresSql(ctx, key, resource) {
|
|
3011
|
-
const literal = quoteLiteral(key);
|
|
3012
|
-
return `(${[`(select ${qualified(ctx, PERMISSION_HELPERS.has)}(${literal}))`, ...(resource === void 0 ? [] : partitionsOf(resource, ctx.scopes)).map((scope) => {
|
|
3013
|
-
const field = scopeField(resource, scope, ctx.scopes) ?? scope;
|
|
3014
|
-
return `${quoteIdent(field)} in (select ${qualified(ctx, checkName(permittedByPermissionHelper(scope)))}(${literal}))`;
|
|
3015
|
-
})].join(" or ")})`;
|
|
3016
|
-
}
|
|
3017
|
-
/**
|
|
3018
|
-
* Postgres truncates an identifier past 63 bytes, which would merge two
|
|
3019
|
-
* helpers.
|
|
3020
|
-
*/
|
|
3021
|
-
function checkName(name) {
|
|
3022
|
-
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`);
|
|
3023
|
-
return name;
|
|
3024
|
-
}
|
|
3025
|
-
function grantsFunction(ctx, grants, renamed, anonExecute) {
|
|
3026
|
-
const fn = qualified(ctx, PERMISSION_HELPERS.grantKeys);
|
|
3027
|
-
const map = Object.fromEntries([...grants].toSorted(byKey));
|
|
3028
|
-
const current = Object.keys(renamed).length === 0 ? "p_permission" : `coalesce(${quoteLiteral(JSON.stringify(renamed))}::jsonb ->> p_permission, p_permission)`;
|
|
3029
|
-
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
|
|
3030
|
-
create or replace function ${fn}(p_permission text, p_scope text, p_effect text default 'allow')
|
|
3031
|
-
returns setof text
|
|
3032
|
-
language sql
|
|
3033
|
-
stable
|
|
3034
|
-
set search_path = ''
|
|
3035
|
-
as $$
|
|
3036
|
-
select g.grant_key
|
|
3037
|
-
from pg_catalog.jsonb_array_elements_text(coalesce(
|
|
3038
|
-
${quoteLiteral(JSON.stringify(map))}::jsonb -> p_scope -> ${current} -> p_effect,
|
|
3039
|
-
'[]'::jsonb
|
|
3040
|
-
)) g(grant_key)
|
|
3041
|
-
$$;
|
|
3042
|
-
${grantsSql(fn, "text, text, text", anonExecute)}`;
|
|
3043
|
-
}
|
|
3044
|
-
function grantsSql(fn, args, anonExecute) {
|
|
3045
|
-
return anonExecute ? `revoke execute on function ${fn}(${args}) from public;
|
|
3046
|
-
grant execute on function ${fn}(${args}) to anon, authenticated;` : `revoke execute on function ${fn}(${args}) from public, anon;
|
|
3047
|
-
grant execute on function ${fn}(${args}) to authenticated;`;
|
|
3048
|
-
}
|
|
3049
|
-
function definerSql(fn, params, returns, sql, parallelSafe) {
|
|
3050
|
-
return `create or replace function ${fn}(${params})
|
|
3051
|
-
returns ${returns}
|
|
3052
|
-
language sql
|
|
3053
|
-
stable
|
|
3054
|
-
security definer
|
|
3055
|
-
cost 1000${parallelSafe ? "\nparallel safe" : ""}
|
|
3056
|
-
set search_path = ''
|
|
3057
|
-
as $$
|
|
3058
|
-
${sql}
|
|
3059
|
-
$$;`;
|
|
3060
|
-
}
|
|
3061
|
-
function heldSql(at, effect) {
|
|
3062
|
-
return `select 1 from pdk_h where pdk_h.key = pdk_k.key and pdk_h.scope = ${quoteLiteral(at)} and pdk_h.effect = '${effect}'`;
|
|
3063
|
-
}
|
|
3064
|
-
function keysFunction(fn, params, body, access, parallelSafe) {
|
|
3065
|
-
return `create or replace function ${fn}(${params})
|
|
3066
|
-
returns setof text
|
|
3067
|
-
${functionBody(body, parallelSafe).replace("set search_path = ''", "set search_path = ''\nset jit = off")}
|
|
3068
|
-
${access}`;
|
|
3069
|
-
}
|
|
3070
|
-
/**
|
|
3071
|
-
* The permission-key forms of the helpers: `grant_keys`, which maps a
|
|
3072
|
-
* permission key to the grant keys of its unconditional allows on a scope (or
|
|
3073
|
-
* every deny key, or the conditioned allow or deny keys),
|
|
3074
|
-
* `permdock_has_permission(p_permission)` and one
|
|
3075
|
-
* `permitted_<scope>_ids_by_permission(p_permission)` per scope, plus their
|
|
3076
|
-
* `_for(p_user, ...)` forms in `database` mode. They answer with the
|
|
3077
|
-
* unconditional allows minus any deny, so a permission whose allows all carry a
|
|
3078
|
-
* row condition answers nothing. The
|
|
3079
|
-
* `permitted_<scope>_ids_by_permission(p_permission, p_conditioned)` overload
|
|
3080
|
-
* with `true` also lists the instances a conditioned allow reaches and
|
|
3081
|
-
* subtracts only unconditional denies, leaving the row condition to the caller,
|
|
3082
|
-
* as `permittedIds(..., { conditioned: true })` does in process.
|
|
3083
|
-
*/
|
|
3084
|
-
function permissionHelpersSql(ctx, grants, renamed, anonExecute) {
|
|
3085
|
-
const parallel = !memoizes(ctx);
|
|
3086
|
-
const definer = (fn, params, returns, sql) => definerSql(fn, params, returns, sql, parallel);
|
|
3087
|
-
const keys = qualified(ctx, PERMISSION_HELPERS.grantKeys);
|
|
3088
|
-
const allowKeys = (scope) => `${keys}(p_permission, ${quoteLiteral(scope)}) g(grant_key)`;
|
|
3089
|
-
const denyKeys = (scope) => `${keys}(p_permission, ${quoteLiteral(scope)}, 'deny') g(grant_key)`;
|
|
3090
|
-
const has = (helper, user) => ` select exists (select 1 from ${allowKeys("global")} where ${helper}(${user}g.grant_key))
|
|
3091
|
-
and not exists (select 1 from ${denyKeys("global")} where ${helper}(${user}g.grant_key))`;
|
|
3092
|
-
const ids = (helper, scope, user) => ` select a.id
|
|
3093
|
-
from ${allowKeys(scope)}
|
|
3094
|
-
cross join lateral ${helper}(${user}g.grant_key) a(id)
|
|
3095
|
-
except
|
|
3096
|
-
select d.id
|
|
3097
|
-
from ${denyKeys(scope)}
|
|
3098
|
-
cross join lateral ${helper}(${user}g.grant_key) d(id)`;
|
|
3099
|
-
const conditionedIds = (helper, scope, user) => ` select a.id
|
|
3100
|
-
from (
|
|
3101
|
-
select g.grant_key from ${allowKeys(scope)}
|
|
3102
|
-
union all
|
|
3103
|
-
select g.grant_key from ${keys}(p_permission, ${quoteLiteral(scope)}, 'conditioned-allow') g(grant_key)
|
|
3104
|
-
where p_conditioned
|
|
3105
|
-
) g
|
|
3106
|
-
cross join lateral ${helper}(${user}g.grant_key) a(id)
|
|
3107
|
-
except
|
|
3108
|
-
select d.id
|
|
3109
|
-
from (
|
|
3110
|
-
select g.grant_key from ${denyKeys(scope)}
|
|
3111
|
-
except
|
|
3112
|
-
select g.grant_key from ${keys}(p_permission, ${quoteLiteral(scope)}, 'conditioned-deny') g(grant_key)
|
|
3113
|
-
where p_conditioned
|
|
3114
|
-
) g
|
|
3115
|
-
cross join lateral ${helper}(${user}g.grant_key) d(id)`;
|
|
3116
|
-
const keysBody = (scope, bodies, filtered) => {
|
|
3117
|
-
const rows = ["global", scope].flatMap((at) => Object.entries(grants.get(at) ?? {}).toSorted(byKey).flatMap(([key, effects]) => ["allow", "deny"].flatMap((effect) => effects[effect].map((grant) => `(${[
|
|
3118
|
-
key,
|
|
3119
|
-
at,
|
|
3120
|
-
effect,
|
|
3121
|
-
grant
|
|
3122
|
-
].map(quoteLiteral).join(", ")})`))));
|
|
3123
|
-
if (new Set(["global", scope].flatMap((at) => Object.entries(grants.get(at) ?? {}).flatMap(([key, effects]) => effects.allow.length > 0 ? [key] : []))).size === 0) return {
|
|
3124
|
-
sql: " select null::text where false",
|
|
3125
|
-
vars: []
|
|
3126
|
-
};
|
|
3127
|
-
const hasBody = bodies.has;
|
|
3128
|
-
const idsBody = bodies.ids(scope);
|
|
3129
|
-
return {
|
|
3130
|
-
sql: ` with pdk_m(key, scope, effect, grant_key) as (
|
|
3131
|
-
values
|
|
3132
|
-
${rows.join(",\n ")}
|
|
3133
|
-
),
|
|
3134
|
-
pdk_w as (
|
|
3135
|
-
select pdk_m.key, pdk_m.scope, pdk_m.effect, pdk_m.grant_key
|
|
3136
|
-
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))` : ""}
|
|
3137
|
-
),
|
|
3138
|
-
pdk_g as (
|
|
3139
|
-
${hasBody.sql}
|
|
3140
|
-
),
|
|
3141
|
-
pdk_s as (
|
|
3142
|
-
select pdk_i.grant_key
|
|
3143
|
-
from (
|
|
3144
|
-
${idsBody.sql}
|
|
3145
|
-
) pdk_i(id, grant_key)
|
|
3146
|
-
where pdk_i.id = p_id
|
|
3147
|
-
),
|
|
3148
|
-
pdk_h as (
|
|
3149
|
-
select pdk_w.key, pdk_w.scope, pdk_w.effect
|
|
3150
|
-
from pdk_w
|
|
3151
|
-
where (pdk_w.scope = 'global' and pdk_w.grant_key in (select pdk_g.grant_key from pdk_g))
|
|
3152
|
-
or (pdk_w.scope = ${quoteLiteral(scope)} and pdk_w.grant_key in (select pdk_s.grant_key from pdk_s))
|
|
3153
|
-
)
|
|
3154
|
-
select pdk_k.key
|
|
3155
|
-
from (select distinct pdk_w.key from pdk_w where pdk_w.effect = 'allow') pdk_k
|
|
3156
|
-
where (exists (${heldSql("global", "allow")}) and not exists (${heldSql("global", "deny")}))
|
|
3157
|
-
or (exists (${heldSql(scope, "allow")}) and not exists (${heldSql(scope, "deny")}))
|
|
3158
|
-
order by 1`,
|
|
3159
|
-
vars: [.../* @__PURE__ */ new Set([...hasBody.vars, ...idsBody.vars])]
|
|
3160
|
-
};
|
|
3161
|
-
};
|
|
3162
|
-
const chunks = [grantsFunction(ctx, grants, renamed, anonExecute), `-- the helpers by permission key: unconditional allows minus any deny
|
|
3163
|
-
${definer(qualified(ctx, PERMISSION_HELPERS.has), "p_permission text", "boolean", has(qualified(ctx, HELPERS.has), ""))}
|
|
3164
|
-
${grantsSql(qualified(ctx, PERMISSION_HELPERS.has), "text", anonExecute)}`];
|
|
3165
|
-
for (const scope of ctx.scopes) {
|
|
3166
|
-
const fn = qualified(ctx, checkName(permittedByPermissionHelper(scope.name)));
|
|
3167
|
-
chunks.push(`${definer(fn, "p_permission text", `setof ${scopeTypeOf(ctx, scope.name)}`, ids(qualified(ctx, permittedIdsHelper(scope.name)), scope.name, ""))}
|
|
3168
|
-
${grantsSql(fn, "text", anonExecute)}`);
|
|
3169
|
-
const keysFn = qualified(ctx, checkName(permissionKeysHelper(scope.name)));
|
|
3170
|
-
const type = scopeTypeOf(ctx, scope.name);
|
|
3171
|
-
const caller = grantBodies({
|
|
3172
|
-
...ctx,
|
|
3173
|
-
grantSet: true
|
|
3174
|
-
});
|
|
3175
|
-
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
|
|
3176
|
-
${keysFunction(keysFn, `p_id ${type}`, keysBody(scope.name, caller, false), grantsSql(keysFn, type, anonExecute), parallel)}
|
|
3177
|
-
${keysFunction(keysFn, `p_id ${type}, p_keys text[]`, keysBody(scope.name, caller, true), grantsSql(keysFn, `${type}, text[]`, anonExecute), parallel)}`);
|
|
3178
|
-
chunks.push(`-- with p_conditioned true, also the instances a conditioned allow reaches, minus only unconditional denies: the caller applies the row condition
|
|
3179
|
-
${definer(fn, "p_permission text, p_conditioned boolean", `setof ${scopeTypeOf(ctx, scope.name)}`, conditionedIds(qualified(ctx, permittedIdsHelper(scope.name)), scope.name, ""))}
|
|
3180
|
-
${grantsSql(fn, "text, boolean", anonExecute)}`);
|
|
3181
|
-
}
|
|
3182
|
-
if (ctx.authorize !== "database") return `${chunks.join("\n\n")}\n`;
|
|
3183
|
-
const user = ctx.dialect === "supabase" ? "uuid" : "text";
|
|
3184
|
-
const revoke = (fn) => `revoke execute on function ${fn}(${user}, text) from public, anon, authenticated;`;
|
|
3185
|
-
const hasFor = qualified(ctx, PERMISSION_HELPERS.hasFor);
|
|
3186
|
-
chunks.push(`-- the same for a user the caller names; no client role may execute them
|
|
3187
|
-
${definer(hasFor, `p_user ${user}, p_permission text`, "boolean", has(qualified(ctx, HELPERS.hasFor), "p_user, "))}
|
|
3188
|
-
${revoke(hasFor)}`);
|
|
3189
|
-
for (const scope of ctx.scopes) {
|
|
3190
|
-
const fn = qualified(ctx, checkName(`${permittedByPermissionHelper(scope.name)}_for`));
|
|
3191
|
-
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, "))}
|
|
3192
|
-
${revoke(fn)}`);
|
|
3193
|
-
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, "))}
|
|
3194
|
-
revoke execute on function ${fn}(${user}, text, boolean) from public, anon, authenticated;`);
|
|
3195
|
-
const keysFor = qualified(ctx, checkName(permissionKeysForHelper(scope.name)));
|
|
3196
|
-
const type = scopeTypeOf(ctx, scope.name);
|
|
3197
|
-
const named = grantBodies({
|
|
3198
|
-
...forUserContext(ctx),
|
|
3199
|
-
grantSet: true
|
|
3200
|
-
});
|
|
3201
|
-
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)}
|
|
3202
|
-
${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)}`);
|
|
3203
|
-
}
|
|
3204
|
-
return `${chunks.join("\n\n")}\n`;
|
|
3205
|
-
}
|
|
3206
|
-
//#endregion
|
|
3207
|
-
//#region src/cli/rls/ownership-names.ts
|
|
3208
|
-
/**
|
|
3209
|
-
* Objects the ownership rules add next to the helpers. Names are part of the
|
|
3210
|
-
* SQL contract.
|
|
3211
|
-
*/
|
|
3212
|
-
const OWNERSHIP = {
|
|
3213
|
-
canAssign: "permdock_can_assign",
|
|
3214
|
-
canAssignFor: "permdock_can_assign_for",
|
|
3215
|
-
canAssignAny: "permdock_can_assign_any",
|
|
3216
|
-
canAssignAnyFor: "permdock_can_assign_any_for",
|
|
3217
|
-
holders: "permdock_holders",
|
|
3218
|
-
transferOnly: "permdock_transfer_only"
|
|
3219
|
-
};
|
|
3220
|
-
/** Objects `rls.assignments` adds. Names are part of the SQL contract. */
|
|
3221
|
-
const ASSIGNMENTS = {
|
|
3222
|
-
custom: "permdock_can_assign_custom_role",
|
|
3223
|
-
customFor: "permdock_can_assign_custom_role_for",
|
|
3224
|
-
trigger: "permdock_assignment"
|
|
3225
|
-
};
|
|
3226
|
-
//#endregion
|
|
3227
|
-
//#region src/cli/rls/ownership-triggers.ts
|
|
3228
|
-
function objectName(prefix, scope) {
|
|
3229
|
-
return quoteIdent(`${prefix}_${scope}`);
|
|
3230
|
-
}
|
|
3231
|
-
/**
|
|
3232
|
-
* Live holders of `roleExpr` in instance `idExpr`, with the same kind and
|
|
3233
|
-
* expiry rules as the helpers.
|
|
3234
|
-
*/
|
|
3235
|
-
function holdersSql(ctx, table, column, idExpr, role, into) {
|
|
3236
|
-
const roleExpr = typeof role === "string" ? quoteLiteral(role) : role.expr;
|
|
3237
|
-
const held = memberRoleOf(table, "m", " ");
|
|
3238
|
-
const filters = [`m.${quoteIdent(column)} = ${idExpr}`, `${held.sql} = ${roleExpr}`];
|
|
3239
|
-
if (table.expiresAt !== void 0) {
|
|
3240
|
-
const expires = memberColumn(table.expiresAt);
|
|
3241
|
-
filters.push(`(${expires} is null or ${expires} > now())`);
|
|
3242
|
-
}
|
|
3243
|
-
const disabled = disabledColumn(table);
|
|
3244
|
-
if (disabled !== void 0) filters.push(`${disabled} is null`);
|
|
3245
|
-
const via = memberVia(table);
|
|
3246
|
-
const kind = typeof role === "string" ? roleKindSql(ctx, role, via) : kindFilterSql(ctx, roleExpr, via);
|
|
3247
|
-
if (kind !== void 0) filters.push(kind);
|
|
3248
|
-
return `select count(distinct m.${quoteIdent(table.user)}) into ${into}
|
|
3249
|
-
from ${quoteQualified(table.table)} m${held.join}
|
|
3250
|
-
where ${filters.join("\n and ")}`;
|
|
3251
|
-
}
|
|
3252
|
-
/**
|
|
3253
|
-
* `min` and `max` as a deferred constraint trigger: checked at commit, so a
|
|
3254
|
-
* transfer (demote one holder, promote another) passes in one transaction. An
|
|
3255
|
-
* instance with no memberships left is being torn down and skips `min`.
|
|
3256
|
-
*/
|
|
3257
|
-
function holdersTriggerSql(ctx, scope, table, column, counted) {
|
|
3258
|
-
const fn = qualified(ctx, `${OWNERSHIP.holders}_${scope}`);
|
|
3259
|
-
const col = quoteIdent(column);
|
|
3260
|
-
const checks = counted.map((rule) => {
|
|
3261
|
-
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")};`];
|
|
3262
|
-
if (rule.min > 0) lines.push(` if v_total > 0 and v_count < ${String(rule.min)} then
|
|
3263
|
-
raise exception using
|
|
3264
|
-
errcode = '23514',
|
|
3265
|
-
message = ${quoteLiteral(`permdock: ${scope} `)} || v_id || ${quoteLiteral(` keeps at least ${String(rule.min)} ${rule.role}`)},
|
|
3266
|
-
hint = 'last-holder';
|
|
3267
|
-
end if;`);
|
|
3268
|
-
if (rule.max !== void 0) lines.push(` if v_count > ${String(rule.max)} then
|
|
3269
|
-
raise exception using
|
|
3270
|
-
errcode = '23514',
|
|
3271
|
-
message = ${quoteLiteral(`permdock: ${scope} `)} || v_id || ${quoteLiteral(` has at most ${String(rule.max)} ${rule.role}`)},
|
|
3272
|
-
hint = 'max-holders';
|
|
3273
|
-
end if;`);
|
|
3274
|
-
return lines.join("\n");
|
|
3275
|
-
});
|
|
3276
|
-
return `-- ${scope}: holder counts (min / max), checked at commit
|
|
3277
|
-
create or replace function ${fn}()
|
|
3278
|
-
returns trigger
|
|
3279
|
-
language plpgsql
|
|
3280
|
-
security definer
|
|
3281
|
-
set search_path = ''
|
|
3282
|
-
as $$
|
|
3283
|
-
declare
|
|
3284
|
-
v_ids text[] := '{}';
|
|
3285
|
-
v_id text;
|
|
3286
|
-
v_key ${quoteQualified(table.table)}.${col}%type;
|
|
3287
|
-
v_total bigint;
|
|
3288
|
-
v_count bigint;
|
|
3289
|
-
begin
|
|
3290
|
-
if tg_op in ('UPDATE', 'DELETE') then
|
|
3291
|
-
v_ids := v_ids || old.${col}::text;
|
|
3292
|
-
end if;
|
|
3293
|
-
if tg_op in ('INSERT', 'UPDATE') then
|
|
3294
|
-
v_ids := v_ids || new.${col}::text;
|
|
3295
|
-
end if;
|
|
3296
|
-
foreach v_id in array v_ids loop
|
|
3297
|
-
continue when v_id is null;
|
|
3298
|
-
v_key := v_id;
|
|
3299
|
-
${checks.join("\n")}
|
|
3300
|
-
end loop;
|
|
3301
|
-
return null;
|
|
3302
|
-
end;
|
|
3303
|
-
$$;
|
|
3304
|
-
drop trigger if exists ${objectName(OWNERSHIP.holders, scope)} on ${quoteQualified(table.table)};
|
|
3305
|
-
create constraint trigger ${objectName(OWNERSHIP.holders, scope)}
|
|
3306
|
-
after insert or update or delete on ${quoteQualified(table.table)}
|
|
3307
|
-
deferrable initially deferred
|
|
3308
|
-
for each row execute function ${fn}();`;
|
|
3309
|
-
}
|
|
3310
|
-
/**
|
|
3311
|
-
* `transferOnly` as statement triggers over transition tables: a statement that
|
|
3312
|
-
* changes a role's holder count in an instance that had holders before and
|
|
3313
|
-
* still has some after is refused. Creating the first holder and removing the
|
|
3314
|
-
* last (which `min` guards) are not transfers.
|
|
3315
|
-
*/
|
|
3316
|
-
function transferTriggerSql(ctx, scope, table, column, roles) {
|
|
3317
|
-
const fn = qualified(ctx, `${OWNERSHIP.transferOnly}_${scope}`);
|
|
3318
|
-
const col = quoteIdent(column);
|
|
3319
|
-
const list = `array[${roles.map(quoteLiteral).join(", ")}]::text[]`;
|
|
3320
|
-
const rows = (alias, source, delta) => {
|
|
3321
|
-
const role = memberRoleOf(table, alias);
|
|
3322
|
-
return `select ${alias}.${col} as id, ${role.sql} as role, ${delta} as delta from ${source} ${alias}${role.join} where ${role.sql} = any(${list})`;
|
|
3323
|
-
};
|
|
3324
|
-
const loop = (source) => ` for v_change in
|
|
3325
|
-
select c.id, c.role, sum(c.delta) as delta
|
|
3326
|
-
from (${source}) c
|
|
3327
|
-
group by c.id, c.role
|
|
3328
|
-
loop
|
|
3329
|
-
continue when v_change.delta = 0 or v_change.id is null;
|
|
3330
|
-
${holdersSql(ctx, table, column, "v_change.id", { expr: "v_change.role" }, "v_after")};
|
|
3331
|
-
if v_after > 0 and v_after - v_change.delta > 0 then
|
|
3332
|
-
raise exception using
|
|
3333
|
-
errcode = '23514',
|
|
3334
|
-
message = 'permdock: ' || v_change.role || ${quoteLiteral(` in ${scope} `)} || v_change.id || ' moves only by transfer',
|
|
3335
|
-
hint = 'transfer-only';
|
|
3336
|
-
end if;
|
|
3337
|
-
end loop;`;
|
|
3338
|
-
const inserted = rows("n", "permdock_new", "1");
|
|
3339
|
-
const deleted = rows("o", "permdock_old", "-1");
|
|
3340
|
-
const target = quoteQualified(table.table);
|
|
3341
|
-
const trigger = (op) => {
|
|
3342
|
-
const name = quoteIdent(`${OWNERSHIP.transferOnly}_${scope}_${op}`);
|
|
3343
|
-
return `drop trigger if exists ${name} on ${target};
|
|
3344
|
-
create trigger ${name}
|
|
3345
|
-
after ${op} on ${target}
|
|
3346
|
-
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"}
|
|
3347
|
-
for each statement execute function ${fn}();`;
|
|
3348
|
-
};
|
|
3349
|
-
return `-- ${scope}: transfer-only roles (${roles.join(", ")}) keep their holder count per statement
|
|
3350
|
-
create or replace function ${fn}()
|
|
3351
|
-
returns trigger
|
|
3352
|
-
language plpgsql
|
|
3353
|
-
security definer
|
|
3354
|
-
set search_path = ''
|
|
3355
|
-
as $$
|
|
3356
|
-
declare
|
|
3357
|
-
v_change record;
|
|
3358
|
-
v_after bigint;
|
|
3359
|
-
begin
|
|
3360
|
-
if tg_op = 'INSERT' then
|
|
3361
|
-
${loop(inserted)}
|
|
3362
|
-
elsif tg_op = 'DELETE' then
|
|
3363
|
-
${loop(deleted)}
|
|
3364
|
-
else
|
|
3365
|
-
${loop(`${inserted} union all ${deleted}`)}
|
|
3366
|
-
end if;
|
|
3367
|
-
return null;
|
|
3368
|
-
end;
|
|
3369
|
-
$$;
|
|
3370
|
-
${trigger("insert")}
|
|
3371
|
-
${trigger("update")}
|
|
3372
|
-
${trigger("delete")}`;
|
|
3373
|
-
}
|
|
3374
|
-
//#endregion
|
|
3375
|
-
//#region src/cli/rls/ownership-sources.ts
|
|
3376
|
-
/**
|
|
3377
|
-
* The membership sources holding scope `name`: `undefined` when there are none,
|
|
3378
|
-
* `'not-tables'` when one of them carries no table to put a trigger on.
|
|
3379
|
-
*/
|
|
3380
|
-
function holderSources(ctx, name) {
|
|
3381
|
-
const sources = memberForSources(ctx, name);
|
|
3382
|
-
if (sources.length === 0) return;
|
|
3383
|
-
const held = [];
|
|
3384
|
-
for (const source of sources) {
|
|
3385
|
-
if (source.sql.holders === void 0) return "not-tables";
|
|
3386
|
-
held.push({
|
|
3387
|
-
table: source.sql.table,
|
|
3388
|
-
holders: source.sql.holders
|
|
3389
|
-
});
|
|
3390
|
-
}
|
|
3391
|
-
return held;
|
|
3392
|
-
}
|
|
3393
|
-
function indent(sql, by) {
|
|
3394
|
-
return sql.replaceAll(/^/gmu, by);
|
|
3395
|
-
}
|
|
3396
|
-
/**
|
|
3397
|
-
* Every source's rows of one instance, each compared with its own typed
|
|
3398
|
-
* `v_key_<n>`.
|
|
3399
|
-
*/
|
|
3400
|
-
function sourceRowsOf(scope, sources) {
|
|
3401
|
-
return sources.map((source, index) => indent(source.holders.rows(scope, { id: `v_key_${String(index)}` }), " ")).join("\n union all\n");
|
|
3402
|
-
}
|
|
3403
|
-
function sourceKeys(sources) {
|
|
3404
|
-
return {
|
|
3405
|
-
declare: sources.map((source, index) => ` v_key_${String(index)} ${source.holders.idType};`).join("\n"),
|
|
3406
|
-
assign: (value, by) => sources.map((_, index) => `${by}v_key_${String(index)} := ${value};`).join("\n")
|
|
3407
|
-
};
|
|
3408
|
-
}
|
|
3409
|
-
function regclassOf(table) {
|
|
3410
|
-
return `${quoteLiteral(quoteQualified(table))}::regclass`;
|
|
3411
|
-
}
|
|
3412
|
-
function sourceTables(sources) {
|
|
3413
|
-
return [...new Set(sources.map((source) => quoteQualified(source.table)))];
|
|
3414
|
-
}
|
|
3415
|
-
/**
|
|
3416
|
-
* `min` and `max` over membership sources: the same commit-time check as on a
|
|
3417
|
-
* mapped table, counted over every source of the scope.
|
|
3418
|
-
*/
|
|
3419
|
-
function sourceHoldersTriggerSql(ctx, scope, sources, counted) {
|
|
3420
|
-
const fn = qualified(ctx, `${OWNERSHIP.holders}_${scope}`);
|
|
3421
|
-
const keys = sourceKeys(sources);
|
|
3422
|
-
const rows = sourceRowsOf(scope, sources);
|
|
3423
|
-
const collect = sources.map((source) => ` if tg_relid = ${regclassOf(source.table)} then
|
|
3424
|
-
if tg_op in ('UPDATE', 'DELETE') then
|
|
3425
|
-
v_ids := v_ids || ${source.holders.id(scope, "old")};
|
|
3426
|
-
end if;
|
|
3427
|
-
if tg_op in ('INSERT', 'UPDATE') then
|
|
3428
|
-
v_ids := v_ids || ${source.holders.id(scope, "new")};
|
|
3429
|
-
end if;
|
|
3430
|
-
end if;`);
|
|
3431
|
-
const checks = counted.map((rule) => {
|
|
3432
|
-
const filters = ["h.live", `h.role = ${quoteLiteral(rule.role)}`];
|
|
3433
|
-
const kind = roleKindSql(ctx, rule.role, "h.via");
|
|
3434
|
-
if (kind !== void 0) filters.push(kind);
|
|
3435
|
-
const lines = [` select count(distinct h.user_id) into v_count
|
|
3436
|
-
from (
|
|
3437
|
-
${rows}
|
|
3438
|
-
) h
|
|
3439
|
-
where ${filters.join("\n and ")};`];
|
|
3440
|
-
if (rule.min > 0) lines.push(` if v_total > 0 and v_count < ${String(rule.min)} then
|
|
3441
|
-
raise exception using
|
|
3442
|
-
errcode = '23514',
|
|
3443
|
-
message = ${quoteLiteral(`permdock: ${scope} `)} || v_id || ${quoteLiteral(` keeps at least ${String(rule.min)} ${rule.role}`)},
|
|
3444
|
-
hint = 'last-holder';
|
|
3445
|
-
end if;`);
|
|
3446
|
-
if (rule.max !== void 0) lines.push(` if v_count > ${String(rule.max)} then
|
|
3447
|
-
raise exception using
|
|
3448
|
-
errcode = '23514',
|
|
3449
|
-
message = ${quoteLiteral(`permdock: ${scope} `)} || v_id || ${quoteLiteral(` has at most ${String(rule.max)} ${rule.role}`)},
|
|
3450
|
-
hint = 'max-holders';
|
|
3451
|
-
end if;`);
|
|
3452
|
-
return lines.join("\n");
|
|
3453
|
-
});
|
|
3454
|
-
const triggers = sourceTables(sources).map((table) => `drop trigger if exists ${objectName(OWNERSHIP.holders, scope)} on ${table};
|
|
3455
|
-
create constraint trigger ${objectName(OWNERSHIP.holders, scope)}
|
|
3456
|
-
after insert or update or delete on ${table}
|
|
3457
|
-
deferrable initially deferred
|
|
3458
|
-
for each row execute function ${fn}();`);
|
|
3459
|
-
return `-- ${scope}: holder counts (min / max) over the membership sources, checked at commit
|
|
3460
|
-
create or replace function ${fn}()
|
|
3461
|
-
returns trigger
|
|
3462
|
-
language plpgsql
|
|
3463
|
-
security definer
|
|
3464
|
-
set search_path = ''
|
|
3465
|
-
as $$
|
|
3466
|
-
declare
|
|
3467
|
-
v_ids text[] := '{}';
|
|
3468
|
-
v_id text;
|
|
3469
|
-
${keys.declare}
|
|
3470
|
-
v_total bigint;
|
|
3471
|
-
v_count bigint;
|
|
3472
|
-
begin
|
|
3473
|
-
${collect.join("\n")}
|
|
3474
|
-
foreach v_id in array v_ids loop
|
|
3475
|
-
continue when v_id is null;
|
|
3476
|
-
${keys.assign("v_id", " ")}
|
|
3477
|
-
select count(*) into v_total
|
|
3478
|
-
from (
|
|
3479
|
-
${rows}
|
|
3480
|
-
) h;
|
|
3481
|
-
${checks.join("\n")}
|
|
3482
|
-
end loop;
|
|
3483
|
-
return null;
|
|
3484
|
-
end;
|
|
3485
|
-
$$;
|
|
3486
|
-
${triggers.join("\n")}`;
|
|
3487
|
-
}
|
|
3488
|
-
function collectChangesSql(changed) {
|
|
3489
|
-
return ` v_changes := v_changes || coalesce((select jsonb_agg(to_jsonb(c)) from (${changed}) c), '[]'::jsonb);`;
|
|
3490
|
-
}
|
|
3491
|
-
/**
|
|
3492
|
-
* `transferOnly` over membership sources: each source table's statement
|
|
3493
|
-
* triggers diff its transition tables, and the count after reads every source.
|
|
3494
|
-
*/
|
|
3495
|
-
function sourceTransferTriggerSql(ctx, scope, sources, roles) {
|
|
3496
|
-
const fn = qualified(ctx, `${OWNERSHIP.transferOnly}_${scope}`);
|
|
3497
|
-
const keys = sourceKeys(sources);
|
|
3498
|
-
const list = `array[${roles.map(quoteLiteral).join(", ")}]::text[]`;
|
|
3499
|
-
const kind = kindFilterSql(ctx, "h.role", "h.via");
|
|
3500
|
-
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})`;
|
|
3501
|
-
const branches = sources.map((source) => ` if tg_relid = ${regclassOf(source.table)} then
|
|
3502
|
-
if tg_op in ('INSERT', 'UPDATE') then
|
|
3503
|
-
${collectChangesSql(changes(source, "permdock_new", "1"))}
|
|
3504
|
-
end if;
|
|
3505
|
-
if tg_op in ('UPDATE', 'DELETE') then
|
|
3506
|
-
${collectChangesSql(changes(source, "permdock_old", "-1"))}
|
|
3507
|
-
end if;
|
|
3508
|
-
end if;`);
|
|
3509
|
-
const triggers = sourceTables(sources).flatMap((table) => [
|
|
3510
|
-
"insert",
|
|
3511
|
-
"update",
|
|
3512
|
-
"delete"
|
|
3513
|
-
].map((op) => {
|
|
3514
|
-
const name = quoteIdent(`${OWNERSHIP.transferOnly}_${scope}_${op}`);
|
|
3515
|
-
return `drop trigger if exists ${name} on ${table};
|
|
3516
|
-
create trigger ${name}
|
|
3517
|
-
after ${op} on ${table}
|
|
3518
|
-
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"}
|
|
3519
|
-
for each statement execute function ${fn}();`;
|
|
3520
|
-
}));
|
|
3521
|
-
return `-- ${scope}: transfer-only roles (${roles.join(", ")}) keep their holder count per statement, over the membership sources
|
|
3522
|
-
create or replace function ${fn}()
|
|
3523
|
-
returns trigger
|
|
3524
|
-
language plpgsql
|
|
3525
|
-
security definer
|
|
3526
|
-
set search_path = ''
|
|
3527
|
-
as $$
|
|
3528
|
-
declare
|
|
3529
|
-
v_changes jsonb := '[]'::jsonb;
|
|
3530
|
-
v_change record;
|
|
3531
|
-
v_after bigint;
|
|
3532
|
-
${keys.declare}
|
|
3533
|
-
begin
|
|
3534
|
-
${branches.join("\n")}
|
|
3535
|
-
for v_change in
|
|
3536
|
-
select x.id, x.role, sum(x.delta) as delta
|
|
3537
|
-
from jsonb_to_recordset(v_changes) x(id text, role text, delta bigint)
|
|
3538
|
-
group by x.id, x.role
|
|
3539
|
-
loop
|
|
3540
|
-
continue when v_change.delta = 0 or v_change.id is null;
|
|
3541
|
-
${keys.assign("v_change.id", " ")}
|
|
3542
|
-
select count(distinct h.user_id) into v_after
|
|
3543
|
-
from (
|
|
3544
|
-
${sourceRowsOf(scope, sources)}
|
|
3545
|
-
) h
|
|
3546
|
-
where h.live
|
|
3547
|
-
and h.role = v_change.role${kind === void 0 ? "" : `\n and ${kind}`};
|
|
3548
|
-
if v_after > 0 and v_after - v_change.delta > 0 then
|
|
3549
|
-
raise exception using
|
|
3550
|
-
errcode = '23514',
|
|
3551
|
-
message = 'permdock: ' || v_change.role || ${quoteLiteral(` in ${scope} `)} || v_change.id || ' moves only by transfer',
|
|
3552
|
-
hint = 'transfer-only';
|
|
3553
|
-
end if;
|
|
3554
|
-
end loop;
|
|
3555
|
-
return null;
|
|
3556
|
-
end;
|
|
3557
|
-
$$;
|
|
3558
|
-
${triggers.join("\n")}`;
|
|
3559
|
-
}
|
|
3560
|
-
function pairsSql(pairs) {
|
|
3561
|
-
return `values ${pairs.map((pair) => `(${quoteLiteral(pair.assigner)}, ${quoteLiteral(pair.role)})`).join(", ")}`;
|
|
3562
|
-
}
|
|
3563
|
-
/**
|
|
3564
|
-
* Membership rows of the membership sources for scope `name`, each source's
|
|
3565
|
-
* `select` comparing its user column with a variable `user` names.
|
|
3566
|
-
*/
|
|
3567
|
-
function sourceRowsSql(sources, user) {
|
|
3568
|
-
const keep = sources.some((source) => source.sql.keeps);
|
|
3569
|
-
return sources.map((source) => source.sql.select(user(source), keep).replaceAll(/^/gmu, " ")).join("\n union all\n");
|
|
3570
|
-
}
|
|
3571
|
-
//#endregion
|
|
3572
|
-
//#region src/cli/rls/graph.ts
|
|
3573
|
-
function tableFor(resource, tables) {
|
|
3574
|
-
return tables?.[resource] ?? resource;
|
|
3575
|
-
}
|
|
3576
|
-
/**
|
|
3577
|
-
* Every `related` condition the policy's grants compile to, with the resource
|
|
3578
|
-
* graph they need, groups included.
|
|
3579
|
-
*/
|
|
3580
|
-
function graphPlan(policy) {
|
|
3581
|
-
const scopes = scopeList(policy.scopes);
|
|
3582
|
-
const plan = /* @__PURE__ */ new Map();
|
|
3583
|
-
const entryFor = (node) => {
|
|
3584
|
-
const entry = plan.get(node.name) ?? {
|
|
3585
|
-
node,
|
|
3586
|
-
relations: /* @__PURE__ */ new Set(),
|
|
3587
|
-
links: /* @__PURE__ */ new Set()
|
|
3588
|
-
};
|
|
3589
|
-
plan.set(node.name, entry);
|
|
3590
|
-
return entry;
|
|
3591
|
-
};
|
|
3592
|
-
const addRelation = (node, relation) => {
|
|
3593
|
-
const entry = entryFor(node);
|
|
3594
|
-
if (entry.relations.has(relation)) return;
|
|
3595
|
-
entry.relations.add(relation);
|
|
3596
|
-
for (const name of expandRelation(node, relation)) {
|
|
3597
|
-
const spec = node.relations[name];
|
|
3598
|
-
if (!isEdgeRelation(spec) || spec.groups === void 0) continue;
|
|
3599
|
-
for (const { resource, relation: groupRelation } of groupEntries(spec)) {
|
|
3600
|
-
const target = policy.resources.get(resource);
|
|
3601
|
-
if (target !== void 0 && target.name !== node.name) addRelation(target, groupRelation);
|
|
3602
|
-
}
|
|
3603
|
-
}
|
|
3604
|
-
};
|
|
3605
|
-
const addLinks = (hops) => {
|
|
3606
|
-
for (let index = 1; index < hops.length; index += 1) {
|
|
3607
|
-
const from = policy.resources.get(hops[index - 1]?.resource ?? "");
|
|
3608
|
-
const hop = hops[index];
|
|
3609
|
-
if (from !== void 0 && hop !== void 0) entryFor(from).links.add(hop.link);
|
|
3610
|
-
}
|
|
3611
|
-
};
|
|
3612
|
-
const addAbove = (above) => {
|
|
3613
|
-
const node = above === void 0 ? void 0 : policy.resources.get(above.resource);
|
|
3614
|
-
if (above === void 0 || node === void 0) return;
|
|
3615
|
-
const entry = entryFor(node);
|
|
3616
|
-
entry.closure = Math.max(entry.closure ?? 0, above.depth);
|
|
3617
|
-
entry.restrictedAncestors = above;
|
|
3618
|
-
};
|
|
3619
|
-
for (const grant of policy.grants) {
|
|
3620
|
-
const row = policy.resources.get(grant.permission.resource);
|
|
3621
|
-
for (const item of flattenGrantee(grant.to)) {
|
|
3622
|
-
if (item.kind === "inherit") {
|
|
3623
|
-
const inherited = inheritCondition(item, row, policy.resources);
|
|
3624
|
-
addLinks(inherited?.hops ?? []);
|
|
3625
|
-
addAbove(inherited?.restrictedAncestors);
|
|
3626
|
-
continue;
|
|
3627
|
-
}
|
|
3628
|
-
if (item.kind !== "relation") continue;
|
|
3629
|
-
const condition = relationCondition(item, row, scopes, { resources: policy.resources });
|
|
3630
|
-
if (condition?.op !== "related") continue;
|
|
3631
|
-
const node = policy.resources.get(condition.resource);
|
|
3632
|
-
if (node === void 0) continue;
|
|
3633
|
-
addRelation(node, condition.relation);
|
|
3634
|
-
const entry = entryFor(node);
|
|
3635
|
-
if (condition.depth > 0 && isSelfParented(node)) entry.closure = Math.max(entry.closure ?? 0, condition.depth);
|
|
3636
|
-
addLinks(condition.hops ?? []);
|
|
3637
|
-
addAbove(condition.restrictedAncestors);
|
|
3638
|
-
}
|
|
3639
|
-
}
|
|
3640
|
-
return plan;
|
|
3641
|
-
}
|
|
3642
|
-
/** The closure depth per walked resource, as `RlsSqlContext.graph` carries it. */
|
|
3643
|
-
function closureDepths(plan) {
|
|
3644
|
-
const out = {};
|
|
3645
|
-
for (const [name, entry] of plan) if (entry.closure !== void 0) out[name] = entry.closure;
|
|
3646
|
-
return out;
|
|
3647
|
-
}
|
|
3648
|
-
/**
|
|
3649
|
-
* The `permitted_<resource>_ids(relation)` arm for one concrete relation: ids
|
|
3650
|
-
* of `resource` the subject holds it on, directly or through a group. `asked`
|
|
3651
|
-
* are the relation names that include it, so a call for any of them (or for
|
|
3652
|
-
* all, with null) reads this arm.
|
|
3653
|
-
*/
|
|
3654
|
-
function relationArm(ctx, plan, node, relation, asked, tables) {
|
|
3655
|
-
const spec = node.relations[relation];
|
|
3656
|
-
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`);
|
|
3657
|
-
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(", ")}))`;
|
|
3658
|
-
return ` select a.id from (${graphSqlText(relationArmSql(node.name, relation, {
|
|
3659
|
-
resources: new Map([...plan].map(([name, item]) => [name, item.node])),
|
|
3660
|
-
...tables === void 0 ? {} : { tables },
|
|
3661
|
-
qualify: qualifySqlTable,
|
|
3662
|
-
holders: (resource, groupRelation) => [{ text: `select ${qualified(ctx, graphHelper(resource))}(${quoteLiteral(groupRelation)})` }]
|
|
3663
|
-
}), ctx)}) a\n where ${guard}${activeUserSql(ctx).map((part) => ` and ${part}`).join("")}`;
|
|
3664
|
-
}
|
|
3665
|
-
function permittedSql(ctx, plan, entry, tables) {
|
|
3666
|
-
const fn = qualified(ctx, graphHelper(entry.node.name));
|
|
3667
|
-
const asked = [...entry.relations].toSorted();
|
|
3668
|
-
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));
|
|
3669
|
-
if (arms.length === 0) arms.push(" select null::text where false");
|
|
3670
|
-
return `-- ${entry.node.name}: ids the subject holds a relation on (all relations when p_relation is null)
|
|
3671
|
-
create or replace function ${fn}(p_relation text)
|
|
3672
|
-
returns setof text
|
|
3673
|
-
language sql
|
|
3674
|
-
stable
|
|
3675
|
-
security definer
|
|
3676
|
-
cost 1000
|
|
3677
|
-
set search_path = ''
|
|
3678
|
-
as $$
|
|
3679
|
-
${arms.join("\n union\n")}
|
|
3680
|
-
$$;
|
|
3681
|
-
revoke execute on function ${fn}(text) from public, anon;
|
|
3682
|
-
grant execute on function ${fn}(text) to authenticated;`;
|
|
3683
|
-
}
|
|
3684
|
-
/**
|
|
3685
|
-
* `permdock_link_<resource>_<link>(ids)`: ids of `resource` whose link points
|
|
3686
|
-
* into `ids`, read past the table's own policies.
|
|
3687
|
-
*/
|
|
3688
|
-
function linkSql(ctx, node, link, tables) {
|
|
3689
|
-
const spec = Object.hasOwn(node.links, link) ? node.links[link] : void 0;
|
|
3690
|
-
if (spec === void 0) throw configError(`PermDock CLI: ${node.name} has no link '${link}'`);
|
|
3691
|
-
const fn = qualified(ctx, linkHelper(node.name, link));
|
|
3692
|
-
return `-- ${node.name}.${link}: rows whose ${spec.field} points at one of the given ${spec.resource} ids
|
|
3693
|
-
create or replace function ${fn}(p_ids text[])
|
|
3694
|
-
returns setof text
|
|
3695
|
-
language sql
|
|
3696
|
-
stable
|
|
3697
|
-
security definer
|
|
3698
|
-
cost 1000
|
|
3699
|
-
set search_path = ''
|
|
3700
|
-
as $$
|
|
3701
|
-
select t.${quoteIdent(node.id)}::text from ${quoteQualified(tableFor(node.name, tables))} t
|
|
3702
|
-
where t.${quoteIdent(spec.field)}::text = any(p_ids)
|
|
3703
|
-
$$;
|
|
3704
|
-
revoke execute on function ${fn}(text[]) from public, anon;
|
|
3705
|
-
grant execute on function ${fn}(text[]) to authenticated;`;
|
|
3706
|
-
}
|
|
3707
|
-
function closureTableSql(ctx) {
|
|
3708
|
-
const table = qualified(ctx, CLOSURE.table);
|
|
3709
|
-
return `-- the object graph: one row per (ancestor, descendant) within each walked resource's depth,
|
|
3710
|
-
-- never crossing a restricted row; kept current by statement triggers on each self-parented table
|
|
3711
|
-
create table if not exists ${table} (
|
|
3712
|
-
resource text not null,
|
|
3713
|
-
ancestor text not null,
|
|
3714
|
-
descendant text not null,
|
|
3715
|
-
depth integer not null check (depth >= 0),
|
|
3716
|
-
primary key (resource, descendant, ancestor)
|
|
3717
|
-
);
|
|
3718
|
-
create index if not exists ${quoteIdent(`${CLOSURE.table}_ancestor`)} on ${table} (resource, ancestor);
|
|
3719
|
-
alter table ${table} enable row level security;
|
|
3720
|
-
revoke all on table ${table} from anon, authenticated, public;
|
|
3721
|
-
grant select on table ${table} to authenticated;`;
|
|
3722
|
-
}
|
|
3723
|
-
function closureObjectsSql(ctx, entry, depth, tables) {
|
|
3724
|
-
const { node } = entry;
|
|
3725
|
-
const parent = node.parent;
|
|
3726
|
-
if (parent === void 0) return "";
|
|
3727
|
-
const name = node.name;
|
|
3728
|
-
const sqlName = graphSqlName(name) ?? name;
|
|
3729
|
-
const closure = qualified(ctx, CLOSURE.table);
|
|
3730
|
-
const table = quoteQualified(tableFor(name, tables));
|
|
3731
|
-
const id = quoteIdent(node.id);
|
|
3732
|
-
const up = quoteIdent(parent.field);
|
|
3733
|
-
const restricted = restrictedFor(node, "parent");
|
|
3734
|
-
const stop = restricted === void 0 ? "false" : `coalesce(t.${quoteIdent(restricted)}, false)`;
|
|
3735
|
-
const stopParent = restricted === void 0 ? "false" : `coalesce(p.${quoteIdent(restricted)}, false)`;
|
|
3736
|
-
const refresh = qualified(ctx, `${CLOSURE.table}_${sqlName}`);
|
|
3737
|
-
const changed = qualified(ctx, `${CLOSURE.table}_${sqlName}_changed`);
|
|
3738
|
-
const literal = quoteLiteral(name);
|
|
3739
|
-
const restrictedChanged = restricted === void 0 ? "" : ` or n.${quoteIdent(restricted)} is distinct from o.${quoteIdent(restricted)}`;
|
|
3740
|
-
const trigger = (suffix) => quoteIdent(`${CLOSURE.table}_${sqlName}_${suffix}`);
|
|
3741
|
-
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`}
|
|
3742
|
-
drop policy if exists ${quoteIdent(`${CLOSURE.table}_${sqlName}`)} on ${closure};
|
|
3743
|
-
create policy ${quoteIdent(`${CLOSURE.table}_${sqlName}`)} on ${closure}
|
|
3744
|
-
for select to authenticated
|
|
3745
|
-
using (resource = ${literal} and ancestor in (select ${qualified(ctx, graphHelper(name))}(null)));
|
|
3746
|
-
create or replace function ${refresh}(p_ids text[])
|
|
3747
|
-
returns void
|
|
3748
|
-
language plpgsql
|
|
3749
|
-
security definer
|
|
3750
|
-
set search_path = ''
|
|
3751
|
-
as $$
|
|
3752
|
-
declare
|
|
3753
|
-
v_cycle text;
|
|
3754
|
-
v_affected text[];
|
|
3755
|
-
begin
|
|
3756
|
-
with recursive walk(start, next, path) as (
|
|
3757
|
-
select t.${id}, t.${up}, array[t.${id}::text]
|
|
3758
|
-
from ${table} t
|
|
3759
|
-
where t.${id}::text = any(p_ids)
|
|
3760
|
-
union all
|
|
3761
|
-
select walk.start, t.${up}, walk.path || t.${id}::text
|
|
3762
|
-
from walk join ${table} t on t.${id} = walk.next
|
|
3763
|
-
where not (walk.next::text = any(walk.path))
|
|
3764
|
-
)
|
|
3765
|
-
select walk.start::text into v_cycle
|
|
3766
|
-
from walk
|
|
3767
|
-
where walk.next::text = any(walk.path)
|
|
3768
|
-
limit 1;
|
|
3769
|
-
if v_cycle is not null then
|
|
3770
|
-
raise exception 'permdock: % % is its own ancestor', ${literal}, v_cycle
|
|
3771
|
-
using errcode = 'check_violation';
|
|
3772
|
-
end if;
|
|
3773
|
-
with recursive down(id, level) as (
|
|
3774
|
-
select t.${id}, 0
|
|
3775
|
-
from ${table} t
|
|
3776
|
-
where t.${id}::text = any(p_ids) or t.${up}::text = any(p_ids)
|
|
3777
|
-
union
|
|
3778
|
-
select t.${id}, down.level + 1
|
|
3779
|
-
from down join ${table} t on t.${up} = down.id
|
|
3780
|
-
where down.level < ${String(depth)}
|
|
3781
|
-
)
|
|
3782
|
-
select coalesce(array_agg(distinct down.id::text), '{}') into v_affected from down;
|
|
3783
|
-
delete from ${closure} c
|
|
3784
|
-
where c.resource = ${literal}
|
|
3785
|
-
and (c.descendant = any(p_ids) or c.descendant = any(v_affected));
|
|
3786
|
-
insert into ${closure} (resource, ancestor, descendant, depth)
|
|
3787
|
-
with recursive walk(descendant, ancestor, parent, depth, stop) as (
|
|
3788
|
-
select t.${id}::text, t.${id}, t.${up}, 0, ${stop}
|
|
3789
|
-
from ${table} t
|
|
3790
|
-
where t.${id}::text = any(v_affected)
|
|
3791
|
-
union all
|
|
3792
|
-
select walk.descendant, p.${id}, p.${up}, walk.depth + 1, ${stopParent}
|
|
3793
|
-
from walk join ${table} p on p.${id} = walk.parent
|
|
3794
|
-
where not walk.stop and walk.depth < ${String(depth)}
|
|
3795
|
-
)
|
|
3796
|
-
select ${literal}, walk.ancestor::text, walk.descendant, walk.depth from walk
|
|
3797
|
-
on conflict do nothing;
|
|
3798
|
-
end
|
|
3799
|
-
$$;
|
|
3800
|
-
revoke execute on function ${refresh}(text[]) from public, anon, authenticated;
|
|
3801
|
-
create or replace function ${changed}()
|
|
3802
|
-
returns trigger
|
|
3803
|
-
language plpgsql
|
|
3804
|
-
security definer
|
|
3805
|
-
set search_path = ''
|
|
3806
|
-
as $$
|
|
3807
|
-
begin
|
|
3808
|
-
if tg_op = 'TRUNCATE' then
|
|
3809
|
-
delete from ${closure} where resource = ${literal};
|
|
3810
|
-
elsif tg_op = 'INSERT' then
|
|
3811
|
-
perform ${refresh}(array(select n.${id}::text from new_rows n));
|
|
3812
|
-
elsif tg_op = 'DELETE' then
|
|
3813
|
-
perform ${refresh}(array(select o.${id}::text from old_rows o));
|
|
3814
|
-
else
|
|
3815
|
-
perform ${refresh}(array(
|
|
3816
|
-
select n.${id}::text
|
|
3817
|
-
from new_rows n left join old_rows o on o.${id} = n.${id}
|
|
3818
|
-
where o.${id} is null or n.${up} is distinct from o.${up}${restrictedChanged}
|
|
3819
|
-
union
|
|
3820
|
-
select o.${id}::text
|
|
3821
|
-
from old_rows o left join new_rows n on n.${id} = o.${id}
|
|
3822
|
-
where n.${id} is null
|
|
3823
|
-
));
|
|
3824
|
-
end if;
|
|
3825
|
-
return null;
|
|
3826
|
-
end
|
|
3827
|
-
$$;
|
|
3828
|
-
revoke execute on function ${changed}() from public, anon, authenticated;
|
|
3829
|
-
drop trigger if exists ${trigger("insert")} on ${table};
|
|
3830
|
-
create trigger ${trigger("insert")} after insert on ${table}
|
|
3831
|
-
referencing new table as new_rows
|
|
3832
|
-
for each statement execute function ${changed}();
|
|
3833
|
-
drop trigger if exists ${trigger("update")} on ${table};
|
|
3834
|
-
create trigger ${trigger("update")} after update on ${table}
|
|
3835
|
-
referencing old table as old_rows new table as new_rows
|
|
3836
|
-
for each statement execute function ${changed}();
|
|
3837
|
-
drop trigger if exists ${trigger("delete")} on ${table};
|
|
3838
|
-
create trigger ${trigger("delete")} after delete on ${table}
|
|
3839
|
-
referencing old table as old_rows
|
|
3840
|
-
for each statement execute function ${changed}();
|
|
3841
|
-
drop trigger if exists ${trigger("truncate")} on ${table};
|
|
3842
|
-
create trigger ${trigger("truncate")} after truncate on ${table}
|
|
3843
|
-
for each statement execute function ${changed}();
|
|
3844
|
-
select ${refresh}(array(select t.${id}::text from ${table} t));`;
|
|
3845
|
-
}
|
|
3846
|
-
function restrictedRowsHelperSql(ctx, plan, entry, tables) {
|
|
3847
|
-
const above = entry.restrictedAncestors;
|
|
3848
|
-
if (above === void 0) return "";
|
|
3849
|
-
const fn = qualified(ctx, restrictedHelper(entry.node.name));
|
|
3850
|
-
const body = graphSqlText(restrictedRowsSql(above, {
|
|
3851
|
-
resources: new Map([...plan].map(([name, item]) => [name, item.node])),
|
|
3852
|
-
...tables === void 0 ? {} : { tables },
|
|
3853
|
-
qualify: qualifySqlTable,
|
|
3854
|
-
closure: `${helperSchema(ctx)}.${CLOSURE.table}`,
|
|
3855
|
-
closureDepths: closureDepths(plan)
|
|
3856
|
-
}), ctx);
|
|
3857
|
-
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
|
|
3858
|
-
create or replace function ${fn}()
|
|
3859
|
-
returns setof text
|
|
3860
|
-
language sql
|
|
3861
|
-
stable
|
|
3862
|
-
security definer
|
|
3863
|
-
cost 1000
|
|
3864
|
-
set search_path = ''
|
|
3865
|
-
as $$
|
|
3866
|
-
${body}
|
|
3867
|
-
$$;
|
|
3868
|
-
revoke execute on function ${fn}() from public, anon;
|
|
3869
|
-
grant execute on function ${fn}() to authenticated;`;
|
|
3870
|
-
}
|
|
3871
|
-
/** Group resources a resource's asked relations name, other than itself. */
|
|
3872
|
-
function groupTargets(entry) {
|
|
3873
|
-
const out = /* @__PURE__ */ new Set();
|
|
3874
|
-
for (const asked of entry.relations) for (const name of expandRelation(entry.node, asked)) {
|
|
3875
|
-
const spec = entry.node.relations[name];
|
|
3876
|
-
const resources = isEdgeRelation(spec) ? groupEntries(spec).map((group) => group.resource) : [];
|
|
3877
|
-
for (const resource of resources) if (resource !== entry.node.name) out.add(resource);
|
|
3878
|
-
}
|
|
3879
|
-
return [...out].toSorted();
|
|
3880
|
-
}
|
|
3881
|
-
/**
|
|
3882
|
-
* Plan entries by name, each after the group resources its helper calls (SQL
|
|
3883
|
-
* function bodies are checked on create).
|
|
3884
|
-
*/
|
|
3885
|
-
function dependencyOrder(plan) {
|
|
3886
|
-
const out = [];
|
|
3887
|
-
const done = /* @__PURE__ */ new Set();
|
|
3888
|
-
const visit = (name) => {
|
|
3889
|
-
const entry = plan.get(name);
|
|
3890
|
-
if (entry === void 0 || done.has(name)) return;
|
|
3891
|
-
done.add(name);
|
|
3892
|
-
for (const target of groupTargets(entry)) visit(target);
|
|
3893
|
-
out.push(entry);
|
|
3894
|
-
};
|
|
3895
|
-
for (const name of [...plan.keys()].toSorted()) visit(name);
|
|
3896
|
-
return out;
|
|
3897
|
-
}
|
|
3898
|
-
function graphIdsSql(ctx, plan, tables) {
|
|
3899
|
-
return dependencyOrder(plan).filter((entry) => entry.relations.size > 0 || entry.closure !== void 0).map((entry) => permittedSql(ctx, plan, entry, tables)).join("\n");
|
|
3900
|
-
}
|
|
3901
|
-
/**
|
|
3902
|
-
* The graph preamble: `permitted_<resource>_ids` for every resource a graph
|
|
3903
|
-
* grant reads, and the closure table with its triggers for every self-parented
|
|
3904
|
-
* resource a grant walks. Empty when no grant is a graph grant.
|
|
3905
|
-
*/
|
|
3906
|
-
function graphSql(ctx, plan, tables) {
|
|
3907
|
-
if (plan.size === 0) return "";
|
|
3908
|
-
const sqlNames = /* @__PURE__ */ new Map();
|
|
3909
|
-
for (const name of plan.keys()) {
|
|
3910
|
-
const helper = graphHelper(name);
|
|
3911
|
-
const sql = graphSqlName(name) ?? name;
|
|
3912
|
-
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)`);
|
|
3913
|
-
const other = sqlNames.get(sql);
|
|
3914
|
-
if (other !== void 0) throw configError(`PermDock CLI: resources '${other}' and '${name}' both name the SQL helper ${helper}; rename one (permdock doctor PD032)`);
|
|
3915
|
-
sqlNames.set(sql, name);
|
|
3916
|
-
}
|
|
3917
|
-
const entries = dependencyOrder(plan);
|
|
3918
|
-
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))]);
|
|
3919
|
-
const walked = entries.filter((entry) => entry.closure !== void 0);
|
|
3920
|
-
if (walked.length > 0) {
|
|
3921
|
-
chunks.push(closureTableSql(ctx));
|
|
3922
|
-
for (const entry of walked) chunks.push(closureObjectsSql(ctx, entry, entry.closure ?? 0, tables));
|
|
3923
|
-
for (const entry of walked) {
|
|
3924
|
-
const helper = restrictedRowsHelperSql(ctx, plan, entry, tables);
|
|
3925
|
-
if (helper !== "") chunks.push(helper);
|
|
3926
|
-
}
|
|
3927
|
-
}
|
|
3928
|
-
return `${chunks.join("\n\n")}\n`;
|
|
3929
|
-
}
|
|
3930
|
-
//#endregion
|
|
3931
|
-
//#region src/cli/sql/tables.ts
|
|
3932
|
-
/**
|
|
3933
|
-
* The `schema.table` an `rls.tables` entry names, or `resource` when it names
|
|
3934
|
-
* none or is `false`.
|
|
3935
|
-
*/
|
|
3936
|
-
function tableNameOf(entry, resource, tables) {
|
|
3937
|
-
if (entry === void 0 || entry === false) return resource;
|
|
3938
|
-
if (typeof entry === "string") return entry;
|
|
3939
|
-
if ("tableOf" in entry) {
|
|
3940
|
-
const owner = tables?.[entry.tableOf];
|
|
3941
|
-
return typeof owner === "object" && "tableOf" in owner ? entry.tableOf : tableNameOf(owner, entry.tableOf);
|
|
3942
|
-
}
|
|
3943
|
-
return entry.table ?? resource;
|
|
3944
|
-
}
|
|
3945
|
-
/**
|
|
3946
|
-
* `rls.tables` as resource to table name, the `via` objects reduced to their
|
|
3947
|
-
* `table` and the `false` entries left out.
|
|
3948
|
-
*/
|
|
3949
|
-
function tableNames(tables) {
|
|
3950
|
-
return tables === void 0 ? void 0 : Object.fromEntries(Object.entries(tables).filter(([, entry]) => entry !== false).map(([resource, entry]) => [resource, tableNameOf(entry, resource, tables)]));
|
|
3951
|
-
}
|
|
3952
|
-
/**
|
|
3953
|
-
* The resources `rls.tables` marks `false` or `{ tableOf }`: no policies of
|
|
3954
|
-
* their own, their grants only seeded.
|
|
3955
|
-
*/
|
|
3956
|
-
function tablelessResources(tables) {
|
|
3957
|
-
return new Set(Object.entries(tables ?? {}).filter(([, entry]) => entry === false || typeof entry === "object" && "tableOf" in entry).map(([resource]) => resource));
|
|
3958
|
-
}
|
|
3959
|
-
/**
|
|
3960
|
-
* Rejects a `{ tableOf }` entry that names its own resource, a `false` entry or
|
|
3961
|
-
* another `{ tableOf }` entry: the owner must have a table of its own.
|
|
3962
|
-
*/
|
|
3963
|
-
function checkSharedTables(tables) {
|
|
3964
|
-
for (const [resource, entry] of Object.entries(tables ?? {})) {
|
|
3965
|
-
if (typeof entry === "string" || entry === false || !("tableOf" in entry)) continue;
|
|
3966
|
-
const owner = tables?.[entry.tableOf];
|
|
3967
|
-
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`);
|
|
3968
|
-
}
|
|
3969
|
-
}
|
|
3970
|
-
function singular(name) {
|
|
3971
|
-
if (name.endsWith("ies")) return `${name.slice(0, -3)}y`;
|
|
3972
|
-
if (name.endsWith("sses")) return name.slice(0, -2);
|
|
3973
|
-
return name.endsWith("s") && !name.endsWith("ss") ? name.slice(0, -1) : name;
|
|
3974
|
-
}
|
|
3975
|
-
/** The `via` entries of `rls.tables`, by resource. */
|
|
3976
|
-
function resolveVias(tables, scopes, dialect) {
|
|
3977
|
-
const out = {};
|
|
3978
|
-
for (const [resource, entry] of Object.entries(tables ?? {})) {
|
|
3979
|
-
if (typeof entry === "string" || entry === false || "tableOf" in entry) continue;
|
|
3980
|
-
const { via } = entry;
|
|
3981
|
-
const scope = via.scope ?? scopes[0]?.name;
|
|
3982
|
-
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(", ")})`);
|
|
3983
|
-
const name = singular(via.table.slice(via.table.lastIndexOf(".") + 1));
|
|
3984
|
-
out[resource] = {
|
|
3985
|
-
helper: permittedIdsHelper(name),
|
|
3986
|
-
key: via.key ?? `${name}_id`,
|
|
3987
|
-
scope,
|
|
3988
|
-
table: via.table.includes(".") ? via.table : `public.${via.table}`,
|
|
3989
|
-
column: via.column,
|
|
3990
|
-
id: via.id ?? "id",
|
|
3991
|
-
type: via.type ?? (dialect === "supabase" ? "uuid" : "text")
|
|
3992
|
-
};
|
|
3993
|
-
}
|
|
3994
|
-
const helpers = /* @__PURE__ */ new Map();
|
|
3995
|
-
for (const [resource, via] of Object.entries(out)) {
|
|
3996
|
-
const seen = helpers.get(via.helper);
|
|
3997
|
-
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`);
|
|
3998
|
-
helpers.set(via.helper, via);
|
|
3999
|
-
}
|
|
4000
|
-
return Object.keys(out).length === 0 ? void 0 : out;
|
|
4001
|
-
}
|
|
4002
|
-
//#endregion
|
|
4003
|
-
export { byKey as $, tokenScopeAllowsCall as A, memoizes as B, permittedByPermissionHelper as C, scopeTable as Ct, memoReadsSql as D, activeUserSql as Dt, helpersSql as E, activeRowSql as Et, disabledColumn as F, roleRows as G, sourcesKeep as H, memberColumn as I, hasCustomRoleChecksFor as J, globalRoleSource as K, memoDiscriminatorSql as L, memoReadTriggersSql as M, capabilityAccessSql as N, seedSql as O, checkSuspension as Ot, claimKeptLines as P, byCodeUnit as Q, memoReadSql as R, permissionKeysForHelper as S, scopeSources as St, accessSql as T, activeMembershipSql as Tt, globalRoleRows as U, sourceFilters as V, membershipRows as W, rolesTableScope as X, raiseSql as Y, storedTenant as Z, ASSIGNMENTS as _, memberOfHelper as _t, tablelessResources as a, graphHelper as at, checkName as b, permittedIdsHelper as bt, graphPlan as c, hasMemberFor as ct, pairsSql as d, isTeamScope as dt, API_KEY_ALLOWS as et, sourceHoldersTriggerSql as f, linkHelper as ft, transferTriggerSql as g, memberIdsHelper as gt, holdersTriggerSql as h, memberForTable as ht, tableNames as i, CLOSURE as it, tokenScopesPlan as j, TOKEN_SCOPE_ALLOWS as k, graphSql as l, hasPermittedUsers as lt, sourceTransferTriggerSql as m, memberForSources as mt, resolveVias as n, apiKeyFields as nt, closureDepths as o, graphSqlName as ot, sourceRowsSql as p, memberForHelper as pt, currentKeyExpr as q, tableNameOf as r, apiKeysPlan as rt, graphIdsSql as s, graphSqlText as st, checkSharedTables as t, apiKeyAllowsCall as tt, holderSources as u, inheritedRowsHelper as ut, OWNERSHIP as v, memberRoleOf as vt, requiresSql as w, activeInstancesSql as wt, permissionHelpersSql as x, restrictedHelper as xt, PERMISSION_HELPERS as y, permittedForHelper as yt, memoWriteSql as z };
|