reactiveadmin 0.2.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.
Files changed (260) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +88 -0
  3. data/LICENSE +21 -0
  4. data/README.md +81 -0
  5. data/app/assets/reactive_admin/bridge.js +89 -0
  6. data/app/controllers/reactive_admin/api_controller.rb +30 -0
  7. data/app/controllers/reactive_admin/client_errors_controller.rb +38 -0
  8. data/app/controllers/reactive_admin/manifest_controller.rb +10 -0
  9. data/app/controllers/reactive_admin/mcp_controller.rb +48 -0
  10. data/app/controllers/reactive_admin/openapi_controller.rb +13 -0
  11. data/app/controllers/reactive_admin/session_controller.rb +11 -0
  12. data/app/views/layouts/reactive_admin/embed.html.erb +30 -0
  13. data/lib/generators/reactiveadmin/install/install_generator.rb +341 -0
  14. data/lib/generators/reactiveadmin/install/templates/menu.rb.tt +25 -0
  15. data/lib/generators/reactiveadmin/install/templates/reactive_admin.rb.tt +53 -0
  16. data/lib/generators/reactiveadmin/install/templates/reactive_admin_annotated.rb.tt +110 -0
  17. data/lib/reactive_admin/aa/v3/controller.rb +76 -0
  18. data/lib/reactive_admin/aa/v3/forms.rb +29 -0
  19. data/lib/reactive_admin/aa/v3/inputs/filters/typeahead_input.rb +51 -0
  20. data/lib/reactive_admin/aa/v3/inputs/typeahead_input.rb +8 -0
  21. data/lib/reactive_admin/aa/v3/install.rb +36 -0
  22. data/lib/reactive_admin/aa/v3/menu.rb +67 -0
  23. data/lib/reactive_admin/aa/v3/presenters.rb +102 -0
  24. data/lib/reactive_admin/aa/v3/registry.rb +78 -0
  25. data/lib/reactive_admin/aa/v3/views.rb +63 -0
  26. data/lib/reactive_admin/aa/v3.rb +23 -0
  27. data/lib/reactive_admin/aa/v4.rb +59 -0
  28. data/lib/reactive_admin/aa.rb +46 -0
  29. data/lib/reactive_admin/action_items.rb +39 -0
  30. data/lib/reactive_admin/action_links.rb +197 -0
  31. data/lib/reactive_admin/action_safety.rb +19 -0
  32. data/lib/reactive_admin/actions.rb +95 -0
  33. data/lib/reactive_admin/api_errors.rb +116 -0
  34. data/lib/reactive_admin/api_fallback.rb +15 -0
  35. data/lib/reactive_admin/api_guards.rb +445 -0
  36. data/lib/reactive_admin/audit.rb +72 -0
  37. data/lib/reactive_admin/auth/guard.rb +68 -0
  38. data/lib/reactive_admin/auth/token_requests.rb +15 -0
  39. data/lib/reactive_admin/auth.rb +135 -0
  40. data/lib/reactive_admin/authorizer.rb +47 -0
  41. data/lib/reactive_admin/background_requests.rb +33 -0
  42. data/lib/reactive_admin/batch_actions.rb +57 -0
  43. data/lib/reactive_admin/choices.rb +289 -0
  44. data/lib/reactive_admin/client_error.rb +70 -0
  45. data/lib/reactive_admin/composite_keys.rb +12 -0
  46. data/lib/reactive_admin/configuration.rb +221 -0
  47. data/lib/reactive_admin/controller_extension.rb +229 -0
  48. data/lib/reactive_admin/csv_injection.rb +26 -0
  49. data/lib/reactive_admin/date_bound.rb +31 -0
  50. data/lib/reactive_admin/degradation.rb +72 -0
  51. data/lib/reactive_admin/diagnostics.rb +16 -0
  52. data/lib/reactive_admin/doctor.rb +466 -0
  53. data/lib/reactive_admin/dry_run.rb +147 -0
  54. data/lib/reactive_admin/dry_run_flag.rb +18 -0
  55. data/lib/reactive_admin/embed.rb +73 -0
  56. data/lib/reactive_admin/engine.rb +47 -0
  57. data/lib/reactive_admin/error_keys.rb +23 -0
  58. data/lib/reactive_admin/exposure.rb +86 -0
  59. data/lib/reactive_admin/filters.rb +165 -0
  60. data/lib/reactive_admin/fixtures/scrubber.rb +1075 -0
  61. data/lib/reactive_admin/fixtures.rb +161 -0
  62. data/lib/reactive_admin/form_content.rb +78 -0
  63. data/lib/reactive_admin/form_field.rb +279 -0
  64. data/lib/reactive_admin/form_has_many.rb +116 -0
  65. data/lib/reactive_admin/form_lock.rb +71 -0
  66. data/lib/reactive_admin/form_payload.rb +57 -0
  67. data/lib/reactive_admin/form_recorder.rb +192 -0
  68. data/lib/reactive_admin/form_schema.rb +160 -0
  69. data/lib/reactive_admin/frame.rb +97 -0
  70. data/lib/reactive_admin/html_nodes.rb +390 -0
  71. data/lib/reactive_admin/html_policy.rb +338 -0
  72. data/lib/reactive_admin/html_rich.rb +186 -0
  73. data/lib/reactive_admin/implicit_defaults.rb +102 -0
  74. data/lib/reactive_admin/index_options.rb +41 -0
  75. data/lib/reactive_admin/index_payload.rb +259 -0
  76. data/lib/reactive_admin/index_recorder.rb +115 -0
  77. data/lib/reactive_admin/index_views.rb +85 -0
  78. data/lib/reactive_admin/inline_style.rb +125 -0
  79. data/lib/reactive_admin/labels_payload.rb +34 -0
  80. data/lib/reactive_admin/ladder.rb +268 -0
  81. data/lib/reactive_admin/layout_classes.rb +167 -0
  82. data/lib/reactive_admin/legacy_inventory.rb +547 -0
  83. data/lib/reactive_admin/location.rb +22 -0
  84. data/lib/reactive_admin/lookup_audit.rb +30 -0
  85. data/lib/reactive_admin/lookup_payload.rb +41 -0
  86. data/lib/reactive_admin/manifest.rb +36 -0
  87. data/lib/reactive_admin/masked_json.rb +62 -0
  88. data/lib/reactive_admin/masking.rb +100 -0
  89. data/lib/reactive_admin/mcp/access.rb +111 -0
  90. data/lib/reactive_admin/mcp/api.rb +123 -0
  91. data/lib/reactive_admin/mcp/count_tool.rb +22 -0
  92. data/lib/reactive_admin/mcp/layout.rb +175 -0
  93. data/lib/reactive_admin/mcp/output.rb +46 -0
  94. data/lib/reactive_admin/mcp/prompts.rb +111 -0
  95. data/lib/reactive_admin/mcp/server.rb +134 -0
  96. data/lib/reactive_admin/mcp/shapes.rb +164 -0
  97. data/lib/reactive_admin/mcp/tools.rb +386 -0
  98. data/lib/reactive_admin/mcp.rb +53 -0
  99. data/lib/reactive_admin/media_nodes.rb +34 -0
  100. data/lib/reactive_admin/menu.rb +90 -0
  101. data/lib/reactive_admin/menu_overlay.rb +291 -0
  102. data/lib/reactive_admin/node_registry.rb +47 -0
  103. data/lib/reactive_admin/open_api/builder.rb +156 -0
  104. data/lib/reactive_admin/open_api/context.rb +46 -0
  105. data/lib/reactive_admin/open_api/core.rb +51 -0
  106. data/lib/reactive_admin/open_api/operation_ids.rb +18 -0
  107. data/lib/reactive_admin/open_api/page_doc.rb +75 -0
  108. data/lib/reactive_admin/open_api/parts.rb +86 -0
  109. data/lib/reactive_admin/open_api/resource_doc.rb +423 -0
  110. data/lib/reactive_admin/open_api/security.rb +55 -0
  111. data/lib/reactive_admin/open_api/write_schema.rb +104 -0
  112. data/lib/reactive_admin/open_api.rb +41 -0
  113. data/lib/reactive_admin/option_source.rb +36 -0
  114. data/lib/reactive_admin/option_sources.rb +14 -0
  115. data/lib/reactive_admin/options_payload.rb +61 -0
  116. data/lib/reactive_admin/page_controller_extension.rb +112 -0
  117. data/lib/reactive_admin/page_forms.rb +181 -0
  118. data/lib/reactive_admin/page_payload.rb +120 -0
  119. data/lib/reactive_admin/param_normalizer.rb +89 -0
  120. data/lib/reactive_admin/paths.rb +63 -0
  121. data/lib/reactive_admin/permissions.rb +31 -0
  122. data/lib/reactive_admin/provenance.rb +57 -0
  123. data/lib/reactive_admin/query_guard.rb +108 -0
  124. data/lib/reactive_admin/ransack_guard.rb +107 -0
  125. data/lib/reactive_admin/rate_limit.rb +59 -0
  126. data/lib/reactive_admin/reactive_dsl.rb +99 -0
  127. data/lib/reactive_admin/readiness.rb +189 -0
  128. data/lib/reactive_admin/registry.rb +69 -0
  129. data/lib/reactive_admin/resource_meta.rb +120 -0
  130. data/lib/reactive_admin/resource_summary.rb +41 -0
  131. data/lib/reactive_admin/routes.rb +60 -0
  132. data/lib/reactive_admin/row_errors.rb +29 -0
  133. data/lib/reactive_admin/rspec.rb +116 -0
  134. data/lib/reactive_admin/scrubbed_error.rb +22 -0
  135. data/lib/reactive_admin/search.rb +79 -0
  136. data/lib/reactive_admin/server_timing.rb +31 -0
  137. data/lib/reactive_admin/show_payload.rb +88 -0
  138. data/lib/reactive_admin/sidebars.rb +34 -0
  139. data/lib/reactive_admin/site.rb +55 -0
  140. data/lib/reactive_admin/style_report.rb +129 -0
  141. data/lib/reactive_admin/style_sources.rb +83 -0
  142. data/lib/reactive_admin/template_actions.rb +126 -0
  143. data/lib/reactive_admin/template_content.rb +49 -0
  144. data/lib/reactive_admin/template_form.rb +442 -0
  145. data/lib/reactive_admin/test_support.rb +31 -0
  146. data/lib/reactive_admin/typeahead.rb +33 -0
  147. data/lib/reactive_admin/ui/assets.rb +91 -0
  148. data/lib/reactive_admin/ui/client_build.rb +47 -0
  149. data/lib/reactive_admin/ui/helper.rb +24 -0
  150. data/lib/reactive_admin/ui/packaged_client.rb +67 -0
  151. data/lib/reactive_admin/ui/shell.rb +81 -0
  152. data/lib/reactive_admin/ui/switch.rb +38 -0
  153. data/lib/reactive_admin/ui.rb +43 -0
  154. data/lib/reactive_admin/value_payload.rb +147 -0
  155. data/lib/reactive_admin/value_token.rb +36 -0
  156. data/lib/reactive_admin/values.rb +43 -0
  157. data/lib/reactive_admin/version.rb +3 -0
  158. data/lib/reactive_admin/write_audit.rb +60 -0
  159. data/lib/reactive_admin/write_guards.rb +142 -0
  160. data/lib/reactive_admin.rb +153 -0
  161. data/lib/reactiveadmin.rb +1 -0
  162. data/lib/tasks/reactiveadmin.rake +36 -0
  163. data/lib/tasks/reactiveadmin_client.rake +11 -0
  164. data/lib/tasks/reactiveadmin_legacy.rake +7 -0
  165. data/lib/tasks/reactiveadmin_styles.rake +6 -0
  166. data/openapi/core.yaml +1643 -0
  167. data/vendor/client/assets/ActionPage-XUYorI8E.js +1 -0
  168. data/vendor/client/assets/ActionView-BsZFcsgp.js +1 -0
  169. data/vendor/client/assets/CommandPalette-C59HT1ip.js +1 -0
  170. data/vendor/client/assets/DatePicker-DuaK0iMg.js +1 -0
  171. data/vendor/client/assets/DateRangeCalendar-B2BDsG-X.js +1 -0
  172. data/vendor/client/assets/DegradedNotice-DiH5n2DO.js +1 -0
  173. data/vendor/client/assets/FormDialog-pmYl8Eov.js +1 -0
  174. data/vendor/client/assets/FormSkeleton-DuSBZO3C.js +1 -0
  175. data/vendor/client/assets/FrameView-2X8cFvUt.css +1 -0
  176. data/vendor/client/assets/FrameView-zmUeDO8d.js +1 -0
  177. data/vendor/client/assets/GroupOverview-DI5T3k5K.js +1 -0
  178. data/vendor/client/assets/InlineForm-CMEIMgeh.js +1 -0
  179. data/vendor/client/assets/JsonDiff-o7JWr7CH.js +3 -0
  180. data/vendor/client/assets/JsonEditor-D4VXdlEx.js +1 -0
  181. data/vendor/client/assets/JsonView-BrJLDmSN.js +1 -0
  182. data/vendor/client/assets/MobileMenu-GAeFOeEb.js +1 -0
  183. data/vendor/client/assets/Node-SQl61V4K.js +2 -0
  184. data/vendor/client/assets/PageView-C-laNEPZ.js +1 -0
  185. data/vendor/client/assets/ResourceForm-BPjsoCY6.js +1 -0
  186. data/vendor/client/assets/ResourceIndex-COezAw5t.js +3 -0
  187. data/vendor/client/assets/ResourceOrPage-CRZGCY84.js +1 -0
  188. data/vendor/client/assets/ResourceShow-DweRXn18.js +1 -0
  189. data/vendor/client/assets/Segmented-BE9TCbph.js +1 -0
  190. data/vendor/client/assets/Sidebars-CsB9rFqX.js +1 -0
  191. data/vendor/client/assets/breadcrumb-DSA3Tlyd.js +1 -0
  192. data/vendor/client/assets/button-CvZ4_DFC.js +1 -0
  193. data/vendor/client/assets/calendar-BoyMpJIf.js +1 -0
  194. data/vendor/client/assets/check-C5A3J16N.js +1 -0
  195. data/vendor/client/assets/command-CMuk0oAt.js +1 -0
  196. data/vendor/client/assets/dist-CqEI82S_.js +1 -0
  197. data/vendor/client/assets/dist-IW4yX942.js +1 -0
  198. data/vendor/client/assets/editor-yqRLzgsJ.js +2 -0
  199. data/vendor/client/assets/external-link-C2aR4slL.js +1 -0
  200. data/vendor/client/assets/frames-C9gPCc3N.js +1 -0
  201. data/vendor/client/assets/humanize-DtU_Kpr4.js +1 -0
  202. data/vendor/client/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  203. data/vendor/client/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  204. data/vendor/client/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  205. data/vendor/client/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  206. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  207. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  208. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  209. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  210. data/vendor/client/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  211. data/vendor/client/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  212. data/vendor/client/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  213. data/vendor/client/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  214. data/vendor/client/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  215. data/vendor/client/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  216. data/vendor/client/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  217. data/vendor/client/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  218. data/vendor/client/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  219. data/vendor/client/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  220. data/vendor/client/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  221. data/vendor/client/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  222. data/vendor/client/assets/ibm-plex-sans-cyrillic-ext-wght-normal-d45eAU9y.woff2 +0 -0
  223. data/vendor/client/assets/ibm-plex-sans-cyrillic-wght-normal-BAAhND-U.woff2 +0 -0
  224. data/vendor/client/assets/ibm-plex-sans-greek-wght-normal-CmyJS8uq.woff2 +0 -0
  225. data/vendor/client/assets/ibm-plex-sans-latin-ext-wght-normal-CIII54If.woff2 +0 -0
  226. data/vendor/client/assets/ibm-plex-sans-latin-wght-normal-IvpUvPa2.woff2 +0 -0
  227. data/vendor/client/assets/ibm-plex-sans-vietnamese-wght-normal-Dg1JeJN0.woff2 +0 -0
  228. data/vendor/client/assets/index-B51aUaAY.js +43 -0
  229. data/vendor/client/assets/index-Cs9rCoWM.css +2 -0
  230. data/vendor/client/assets/input-DByFmQPa.js +1 -0
  231. data/vendor/client/assets/json-De3PN-R6.css +1 -0
  232. data/vendor/client/assets/json-oTp7Q-d-.js +5 -0
  233. data/vendor/client/assets/media-D4a_En8R.js +1 -0
  234. data/vendor/client/assets/plus-CfJ9vo8X.js +1 -0
  235. data/vendor/client/assets/popover-CDtI9R8Q.js +1 -0
  236. data/vendor/client/assets/purify-G7QKJyJq.js +1 -0
  237. data/vendor/client/assets/query-CCsZN2fa.js +1 -0
  238. data/vendor/client/assets/recent-BrzLwL0D.js +1 -0
  239. data/vendor/client/assets/rich-BQc_q5T7.js +1 -0
  240. data/vendor/client/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  241. data/vendor/client/assets/select-C43qDA3k.js +1 -0
  242. data/vendor/client/assets/sheet-BPl2n-4n.js +1 -0
  243. data/vendor/client/assets/textarea-BnOphXry.js +1 -0
  244. data/vendor/client/assets/uiMode-z0ZbRV49.js +1 -0
  245. data/vendor/client/assets/uiToggle-DwnRQTH1.js +1 -0
  246. data/vendor/client/assets/useRecordForm-X_DExEP2.js +1 -0
  247. data/vendor/client/assets/useRecordVisit-BRtfMi-q.js +1 -0
  248. data/vendor/client/assets/utils-DwBGbDkG.js +1 -0
  249. data/vendor/client/assets/vendor-calendar-nTZiq9oY.js +1 -0
  250. data/vendor/client/assets/vendor-datefns-BoC6MCnl.js +1 -0
  251. data/vendor/client/assets/vendor-forms-D0h8hG_S.js +55 -0
  252. data/vendor/client/assets/vendor-purify-BXoPR7WT.js +3 -0
  253. data/vendor/client/assets/vendor-query-DZ6APRNI.js +1 -0
  254. data/vendor/client/assets/vendor-react-C1iE8mnY.js +9 -0
  255. data/vendor/client/assets/vendor-router-CI6Vh4k_.js +1 -0
  256. data/vendor/client/assets/vendor-table-DuQ835by.js +4 -0
  257. data/vendor/client/index.html +24 -0
  258. data/vendor/client/manifest.json +867 -0
  259. data/vendor/client/reactiveadmin-client.json +4 -0
  260. metadata +350 -0
@@ -0,0 +1,86 @@
1
+ module ReactiveAdmin
2
+ module OpenApi
3
+ # Building blocks shared by the resource and page documents.
4
+ module Parts
5
+ VERBS = %w[get put post patch delete].freeze
6
+ ERRORS = {
7
+ 400 => "BadRequest", 401 => "Unauthorized", 403 => "Forbidden", 404 => "NotFound",
8
+ 409 => "Conflict", 422 => "Invalid", 429 => "RateLimited"
9
+ }.freeze
10
+ DEGRADED = {"X-Reactiveadmin-Degraded": {"$ref": "#/components/headers/Degraded"}}.freeze
11
+
12
+ module_function
13
+
14
+ def ref(kind, name) = {"$ref": "#/components/#{kind}/#{name}"}
15
+
16
+ def schema_ref(name) = ref("schemas", name)
17
+
18
+ def shared(name) = ref("responses", name)
19
+
20
+ def json(schema) = {"application/json": {schema:}}
21
+
22
+ def success(description, schema, degraded: false, type: "application/json")
23
+ {description:, **({headers: DEGRADED} if degraded), content: {type => {schema:}}}.compact
24
+ end
25
+
26
+ def error_responses(codes) = codes.sort.to_h { [it.to_s, ref("responses", ERRORS.fetch(it))] }
27
+
28
+ # Query parameter for a deepObject map, e.g. `q[title_cont]=x`.
29
+ def deep_object(name, properties, description:)
30
+ {name:, in: "query", style: "deepObject", explode: true, description:,
31
+ schema: {type: "object", properties:, additionalProperties: false}}
32
+ end
33
+
34
+ # A GET form's fields depend on what its view renders, which a document built from declarations can't read: the
35
+ # operation takes them as free-form query parameters named by the form's field params, e.g. `simulation[date]`.
36
+ def form_query_param
37
+ {name: "form_fields", in: "query", style: "form", explode: true, required: false,
38
+ description: "Fields of the view's GET form, named by each field's `param` (`simulation[date]=2026-10-01`; lists as `tags[]`). The response's `form` nodes list them with their current values.",
39
+ schema: {type: "object", additionalProperties: true}}
40
+ end
41
+
42
+ def path_param(name, description = nil) = {name:, in: "path", required: true, description:, schema: {type: "string"}}.compact
43
+
44
+ def camel(name) = name.to_s.camelize
45
+
46
+ # An operation, with the standard error responses for the codes it can answer. Reads inherit the
47
+ # document's security; writes also need the CSRF token.
48
+ def operation(id:, summary:, tags:, responses:, write: false, description: nil, parameters: nil, request_body: nil, errors: [])
49
+ {
50
+ operationId: id, summary:, description:, tags:, parameters: parameters.presence, requestBody: request_body,
51
+ responses: responses.merge(error_responses([401, 429, *errors].uniq)).sort_by { |code, _| code.to_s }.to_h,
52
+ security: (Security.requirement(write: true) if write)
53
+ }.compact
54
+ end
55
+
56
+ # What the guards of an action say of its operation: a session-only one, or one a registered guard may refuse.
57
+ def guard_extensions(config, names)
58
+ names = names.map(&:to_s)
59
+ custom = ApiGuards.custom_for(config, names)
60
+ {"x-reactiveadmin-session-only": (true if ApiGuards.session_only?(config, names)), "x-reactiveadmin-guard": custom&.name}.compact
61
+ end
62
+
63
+ # Verbs of a declared action (`member_action :x, method: [:get, :post]`).
64
+ def verbs_of(declaration)
65
+ Array.wrap(declaration.http_verb).map { it.to_s.downcase } & VERBS
66
+ end
67
+
68
+ error = ->(description) { {description:, content: json(schema_ref("Error"))} }
69
+ # Responses every resource repeats, defined once under components.
70
+ RESPONSES = {
71
+ "Unauthorized" => error.call("Not signed in (`unauthorized`)."),
72
+ "Forbidden" => error.call("The user may not do this (`forbidden`), a bearer token lacks the scope (`insufficient_scope`), or an `api` guard refuses it (`api_denied`, with `guard` and `classic_url`)."),
73
+ "NotFound" => error.call("No such record, or the resource is not served (`not_found`)."),
74
+ "ShowOk" => success("The show page's layout", schema_ref("ShowResponse"), degraded: true),
75
+ "FormOk" => success("The form, as the client renders it", schema_ref("FormResponse"), degraded: true),
76
+ "Created" => success("Created", schema_ref("WriteResult")),
77
+ "Written" => success("The write was applied", schema_ref("WriteResult")),
78
+ "MetaOk" => success("Resource metadata", schema_ref("ResourceMeta")),
79
+ "OptionsOk" => success("Matching options", schema_ref("OptionsResponse")),
80
+ "LookupOk" => success("Options per requested field", schema_ref("LookupResponse")),
81
+ "LabelsOk" => success("Labels of the readable records", schema_ref("LabelsResponse")),
82
+ "ValueOk" => success("The full value", schema_ref("ValueResponse"))
83
+ }.freeze
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,423 @@
1
+ module ReactiveAdmin
2
+ module OpenApi
3
+ # The paths, schemas and tag of one resource, for the actions it defines and the user may take.
4
+ # Declarations only: filters without option lists, scopes, sortable columns, the controls-only form.
5
+ class ResourceDoc
6
+ include Parts
7
+
8
+ CELL_TYPES = {
9
+ integer: %w[number], float: %w[number], decimal: %w[number], boolean: %w[boolean], date: %w[date],
10
+ datetime: %w[datetime], time: %w[datetime], string: %w[text], text: %w[text], json: %w[json], jsonb: %w[json]
11
+ }.freeze
12
+ BATCH_INPUTS = {
13
+ "text" => {type: "string"}, "textarea" => {type: "string"}, "select" => {type: "string"}, "number" => {type: "number"},
14
+ "date" => {type: "string", format: "date"}, "boolean" => {type: "boolean"}
15
+ }.freeze
16
+ EMPTY_DECLARED = {filters: [], scopes: [], batch_actions: [], download_formats: []}.freeze
17
+
18
+ attr_reader :paths, :schemas, :parameters
19
+
20
+ def initialize(context, summary)
21
+ @ctx = context
22
+ @summary = summary
23
+ @key = summary[:key]
24
+ @config = Registry.find(@key)
25
+ @permissions = summary[:permissions]
26
+ @actions = summary[:actions].map(&:to_sym)
27
+ @nested = Paths.nested?(@config)
28
+ @plural = camel(@key)
29
+ @singular = camel(@config.resource_name.singular)
30
+ @paths = {}
31
+ @schemas = {}
32
+ @parameters = {}
33
+ end
34
+
35
+ def call
36
+ Degradation.with_collection(resource: @config.resource_name, action: "openapi") do
37
+ probe
38
+ list
39
+ show
40
+ forms
41
+ destroy
42
+ meta_endpoints
43
+ custom_actions
44
+ batch
45
+ export
46
+ end
47
+ {tag: tag, paths:, schemas:, parameters:}
48
+ end
49
+
50
+ private
51
+
52
+ def tag
53
+ {name: @key, "x-displayName": @summary[:plural_label], description: "#{@summary[:plural_label]} (#{@summary[:label]}). Paths of a resource nested under a parent carry the parent's id."}
54
+ end
55
+
56
+ def probe
57
+ controller = @ctx.probe(@config).controller
58
+ @declared = guarded("declarations") { ResourceMeta.new(controller).declared } || EMPTY_DECLARED
59
+ @static = guarded("page sizes") { ResourceMeta.new(controller).static } || {}
60
+ @columns = guarded("index columns") { IndexPayload.new(controller).declared_columns } || []
61
+ @controller = controller
62
+ end
63
+
64
+ # What the resource declares can fail to evaluate; the document then says less rather than nothing.
65
+ def guarded(what)
66
+ yield
67
+ rescue => e
68
+ Degradation.record(kind: :openapi_degraded, where: "openapi/#{@key}/#{what}", reason: "#{what.capitalize} raised #{e.class}; documented generically")
69
+ nil
70
+ end
71
+
72
+ # Denied actions are left out: the server refuses them, so they are not part of the API's surface.
73
+ def allowed?(action, permission = action) = @actions.include?(action) && @permissions[permission] && !ApiGuards.denies?(@config, action, permission)
74
+
75
+ def id(name) = @ctx.ids.claim(name)
76
+
77
+ # `names` are the actions the operation runs: what their guards say is part of it.
78
+ def add(path, verb, operation, names: nil) = ((@paths[path] ||= {})[verb] = names ? operation.merge(guard_extensions(@config, names)) : operation)
79
+
80
+ def tags = [@key]
81
+
82
+ def parent = @summary[:belongs_to]
83
+
84
+ def parent_params = (@nested ? [path_param(parent[:param], "Id of the parent #{parent[:parent].singularize.humanize.downcase}")] : [])
85
+
86
+ def base = @base ||= Paths.api(Paths.collection(@config, parent_id: ("{#{parent[:param]}}" if @nested)))
87
+
88
+ def flat = @flat ||= Paths.api(Paths.collection(@config))
89
+
90
+ def options_path = Paths.api(Paths.options(@config))
91
+
92
+ def record_path = "#{base}/{id}"
93
+
94
+ def id_param = ref("parameters", "Id")
95
+
96
+ # Reads
97
+
98
+ def list
99
+ add(base, "get", operation(
100
+ id: id("list#{@plural}"), summary: "List #{@summary[:plural_label]}", tags:,
101
+ description: "Filtered, scoped, sorted and paginated rows. #{columns_note}".strip,
102
+ parameters: [*parent_params, *query_params, *page_params],
103
+ responses: {200 => success("Rows of the page", schema_ref("#{@plural}IndexResponse"), degraded: true)}, errors: [400, 403]
104
+ ), names: %w[index])
105
+ @schemas["#{@singular}Row"] = row_schema
106
+ @schemas["#{@plural}IndexResponse"] = {
107
+ allOf: [schema_ref("IndexResponse"), {type: "object", properties: {resource: {const: @key}, rows: {type: "array", items: schema_ref("#{@singular}Row")}}}]
108
+ }
109
+ end
110
+
111
+ def show
112
+ return unless allowed?(:show)
113
+
114
+ add(record_path, "get", operation(
115
+ id: id("get#{@singular}"), summary: "Show a #{@summary[:label]}", tags:, parameters: [*parent_params, id_param],
116
+ responses: {200 => shared("ShowOk")}, errors: [403, 404]
117
+ ), names: %w[show])
118
+ end
119
+
120
+ def forms
121
+ add_form("#{base}/new", "getNew#{@singular}Form", "Form for a new #{@summary[:label]}", [*parent_params], :new, :create)
122
+ add_form("#{record_path}/edit", "getEdit#{@singular}Form", "Form to edit a #{@summary[:label]}", [*parent_params, id_param], :edit, :update)
123
+ write_endpoints
124
+ end
125
+
126
+ def add_form(path, operation_id, summary, parameters, action, permission)
127
+ return unless allowed?(action, permission)
128
+
129
+ errors = parameters.include?(id_param) ? [403, 404] : [403]
130
+ add(path, "get", operation(id: id(operation_id), summary:, tags:, parameters:, responses: {200 => shared("FormOk")}, errors:), names: [action, permission])
131
+ end
132
+
133
+ def meta_endpoints
134
+ core_operation("/admin/{resource}/_meta", flat + "/_meta", "get#{@plural}Meta", "MetaOk", summary: "Metadata of #{@summary[:plural_label]}", errors: [403, 404])
135
+ core_operation("/admin/{resource}/_options", flat + "/_options", "get#{@plural}Options", "OptionsOk", summary: "Search options for a filter or form control", errors: [403, 404])
136
+ core_operation("/admin/{resource}/_options/lookup", flat + "/_options/lookup", "lookup#{@plural}Options", "LookupOk", summary: "Labels of selected option values", errors: [400, 403, 404])
137
+ core_operation("/admin/{resource}/_labels", flat + "/_labels", "get#{@plural}Labels", "LabelsOk", summary: "Display names by id", errors: [400, 404]) unless @nested || ApiGuards.denies?(@config, "show")
138
+ if @nested
139
+ core_operation("/admin/{resource}/_options", "#{base}/_options", "get#{@plural}OptionsNested", "OptionsOk", summary: "Search options of a form under its parent", parent: true, errors: [403, 404])
140
+ core_operation("/admin/{resource}/_options/lookup", "#{base}/_options/lookup", "lookup#{@plural}OptionsNested", "LookupOk", summary: "Labels of selected option values under the parent", parent: true, errors: [400, 403, 404])
141
+ end
142
+ value_path = @nested ? "#{base}/{id}/_value" : "#{flat}/{id}/_value"
143
+ core_operation("/admin/{resource}/{id}/_value", value_path, "get#{@singular}Value", "ValueOk", summary: "Full value of a summarized or truncated field", parent: @nested, errors: [403, 404]) if allowed?(:show)
144
+ end
145
+
146
+ # Core's operation as a template, under a concrete path: its first sentence, and its parameters
147
+ # defined once under components rather than for every resource.
148
+ def core_operation(template, path, operation_id, response, summary:, errors:, parent: false)
149
+ source = Core.operation(template, "get")
150
+ parameters = source["parameters"].to_a.reject { it["name"] == "resource" || it["$ref"] == "#/components/parameters/Resource" }.map { hoist(source["operationId"], it) }
151
+ parameters.unshift(*parent_params) if parent
152
+ add(path, "get", operation(id: id(operation_id), summary:, tags:, description: source["description"].to_s.squish.split(/(?<=\.)\s/).first,
153
+ parameters:, responses: {200 => shared(response)}, errors:))
154
+ end
155
+
156
+ def hoist(operation_id, parameter)
157
+ return parameter if parameter.key?("$ref") || parameter["in"] == "path"
158
+
159
+ name = "#{operation_id}#{camel(parameter["name"])}".camelize
160
+ @parameters[name] = parameter
161
+ ref("parameters", name)
162
+ end
163
+
164
+ def export
165
+ return unless allowed?(:index) && @declared[:download_formats].include?("csv")
166
+
167
+ add("#{base}.csv", "get", operation(
168
+ id: id("export#{@plural}Csv"), summary: "Export #{@summary[:plural_label]} as CSV", tags:,
169
+ description: "AA's streamed CSV export of every page of the current filters, scope and order. Masked attributes are replaced by a placeholder. Without a `csv` block it takes the index's attribute columns, or the secure default columns; 422 when that is refused (too many rows, or strict defaults).",
170
+ parameters: [*parent_params, *query_params],
171
+ responses: {200 => success("text/csv attachment", {type: "string", format: "binary"}, type: "text/csv")}, errors: [400, 403, 422]
172
+ ), names: %w[index])
173
+ end
174
+
175
+ # Writes
176
+
177
+ def write_endpoints
178
+ %i[create update].each do |action|
179
+ next unless allowed?(action)
180
+
181
+ body, keys, submittable = write_body(action)
182
+ unsupported = "This form can't be submitted through the API (it holds inputs only the classic admin carries); writes answer 422 `unsupported`." unless submittable
183
+ note = [unsupported, attribute_note(action)].compact.join(" ").presence
184
+ send(:"#{action}_endpoint", body, keys, note)
185
+ end
186
+ end
187
+
188
+ def write_body(action)
189
+ controller = @controller
190
+ form = (@form ||= [guarded("form") do
191
+ FormSchema.new(controller, @config.resource_class.new, controls_only: true).then { [it.sections, it.submittable?] }
192
+ end]).first
193
+ return [{type: "object", additionalProperties: {type: "object", additionalProperties: true}}, [], true] unless form
194
+
195
+ writer = WriteSchema.new(@config, form.first, options_path:, reserved: ApiGuards.reserved_keys(@config, [action.to_s]))
196
+ [writer.schema || {type: "object", additionalProperties: false}, writer.keys, form.last]
197
+ end
198
+
199
+ # What the attribute guards of this write say, in the channel the document is for.
200
+ def attribute_note(action)
201
+ names = [action.to_s]
202
+ applicable = ApiGuards.attributes_of(@config).select { ApiGuards.applies?(it, names) }
203
+ denied = ApiGuards.denied_attributes(@config, names)
204
+ rest = applicable - denied
205
+ [
206
+ listing(denied, "Reserved for the classic admin and not accepted here: %s. A write that includes one answers 403 `api_denied`."),
207
+ listing(rest.select { it.guard == :session_only }, "Accepted only from a signed-in session: %s. A token's write that includes one answers 403 `api_denied`."),
208
+ *rest.reject(&:static?).map { "A write that includes #{ticks(it.attributes)} may be refused by the `#{it.name}` guard (403 `api_denied`)." }
209
+ ].compact.join(" ").presence
210
+ end
211
+
212
+ def listing(declarations, template) = (template % ticks(declarations.flat_map(&:attributes).uniq) if declarations.any?)
213
+
214
+ def ticks(names) = names.map { "`#{it}`" }.join(", ")
215
+
216
+ def create_endpoint(body, keys, note)
217
+ @schemas["#{@singular}CreateParams"] = params_schema(body, keys)
218
+ add(base, "post", operation(
219
+ id: id("create#{@singular}"), summary: "Create a #{@summary[:label]}", tags:, write: true, parameters: parent_params,
220
+ description: ["Body: the form's controls under the resource's param key. Disabled and masked inputs are not accepted.", note].compact.join(" "),
221
+ request_body: {required: true, content: json(schema_ref("#{@singular}CreateParams"))},
222
+ responses: {201 => shared("Created")}, errors: [403, 422]
223
+ ), names: %w[create])
224
+ end
225
+
226
+ def update_endpoint(body, keys, note)
227
+ @schemas["#{@singular}UpdateParams"] = params_schema(body, keys).deep_merge(properties: {lock: schema_ref("FormLock"), dry_run: {type: "boolean", description: "Validate and return the changes (`changes`: attribute to `{from, to}`) without saving. Masked values show as `[masked]`; no write is audited."}})
228
+ add(record_path, "patch", operation(
229
+ id: id("update#{@singular}"), summary: "Update a #{@summary[:label]}", tags:, write: true, parameters: [*parent_params, id_param],
230
+ description: ["Same body as create, plus the `lock` token the edit form handed out (a mismatch is 409 `stale`).", note].compact.join(" "),
231
+ request_body: {required: true, content: json(schema_ref("#{@singular}UpdateParams"))},
232
+ responses: {200 => success("The write was applied, or with `dry_run` the preview of it", {oneOf: [schema_ref("WriteResult"), schema_ref("DryRunResult")]})}, errors: [403, 404, 409, 422]
233
+ ), names: %w[update])
234
+ end
235
+
236
+ def params_schema(body, keys)
237
+ key = @config.param_key.to_s
238
+ {description: "`#{key}` wraps the record's attributes.", **body, **({required: [key]} if keys.include?(key))}
239
+ end
240
+
241
+ def destroy
242
+ return unless allowed?(:destroy)
243
+
244
+ add(record_path, "delete", operation(
245
+ id: id("delete#{@singular}"), summary: "Delete a #{@summary[:label]}", tags:, write: true, parameters: [*parent_params, id_param],
246
+ responses: {200 => shared("Written")}, errors: [403, 404, 409, 422]
247
+ ), names: %w[destroy])
248
+ end
249
+
250
+ # Custom actions: every declared member and collection action the user may take.
251
+
252
+ def custom_actions
253
+ declare_actions(@config.member_actions, member: true)
254
+ declare_actions(@config.collection_actions, member: false)
255
+ end
256
+
257
+ def declare_actions(declarations, member:)
258
+ declarations.sort_by { it.name.to_s }.each do |declaration|
259
+ name = declaration.name.to_s
260
+ next unless @ctx.authorized?(name.to_sym, @config.resource_class, @config)
261
+
262
+ verbs = verbs_of(declaration)
263
+ verbs.each { action_operation(name, it, member:, suffix: (camel(it) if verbs.size > 1)) unless ApiGuards.denies?(@config, name, verb: it) }
264
+ end
265
+ end
266
+
267
+ def action_operation(name, verb, member:, suffix:)
268
+ path = member ? "#{record_path}/#{name}" : "#{base}/#{name}"
269
+ prefix = member ? @singular.camelize(:lower) : @plural.camelize(:lower)
270
+ kind = member ? "Member" : "Collection"
271
+ get = verb == "get"
272
+ add(path, verb, operation(
273
+ id: id("#{prefix}#{camel(name)}#{suffix}"), summary: "#{name.humanize} (#{kind.downcase} action)", tags:, write: !get,
274
+ description: "#{kind} action `#{name}` of #{@summary[:plural_label]}. #{action_note(get)}",
275
+ parameters: [*parent_params, *(member ? [id_param] : []), *([form_query_param] if get && Ladder.action(@config, name)&.get_form)],
276
+ request_body: (ref("requestBodies", "ActionParams") unless get),
277
+ responses: action_responses(get), errors: action_errors(get, verb, member)
278
+ ), names: [name])
279
+ end
280
+
281
+ def action_note(get)
282
+ return "Answers the action's template as a form, or 501 `unsupported` when it renders an html page (use the classic admin)." if get
283
+
284
+ "The action's redirect and flash become the result; an alert or errors answer 422."
285
+ end
286
+
287
+ def action_responses(get)
288
+ return {200 => ref("responses", "ActionResult")} unless get
289
+
290
+ {200 => shared("FormOk"),
291
+ 501 => {description: "The action renders an html page the API can't describe (`unsupported`).", content: json(schema_ref("Error"))}}
292
+ end
293
+
294
+ def action_errors(get, verb, member) = [403, *(404 if member), *(422 unless get), *(409 if %w[put patch].include?(verb))]
295
+
296
+ def batch
297
+ actions = @declared[:batch_actions].reject { it[:api_denied] }
298
+ return if actions.empty? || !allowed?(:index) || ApiGuards.denies?(@config, "batch_action")
299
+
300
+ add("#{base}/batch_action", "post", operation(
301
+ id: id("batch#{@plural}"), summary: "Run a batch action on #{@summary[:plural_label]}", tags:, write: true, parameters: parent_params,
302
+ description: "Runs one of the batch actions the user may use over the selected ids: #{actions.map { "`#{it[:key]}`" }.join(", ")}.",
303
+ request_body: {required: true, content: json({oneOf: actions.map { batch_schema(it) }})},
304
+ responses: {200 => ref("responses", "ActionResult")}, errors: [403, 422]
305
+ ), names: %w[batch_action])
306
+ end
307
+
308
+ def batch_schema(action)
309
+ inputs = action[:inputs].to_h { [it[:name], {description: it[:label], **BATCH_INPUTS.fetch(it[:control], {type: "string"})}] }
310
+ properties = {
311
+ batch_action: {const: action[:key]},
312
+ collection_selection: {type: "array", items: {type: "string"}, description: "Ids of the selected records."},
313
+ **({batch_action_inputs: {type: "object", properties: inputs, additionalProperties: false}} if inputs.any?)
314
+ }
315
+ {type: "object", title: action[:label], description: action[:confirm], required: %w[batch_action collection_selection], properties:,
316
+ "x-reactiveadmin-guard": action[:api_guard]}.compact
317
+ end
318
+
319
+ # Listing parameters
320
+
321
+ def query_params = [filters_param, scope_param, order_param, views_param].compact
322
+
323
+ def page_params
324
+ sizes = [ReactiveAdmin.config.max_per_page, *@static[:per_page_options]].compact.max
325
+ [{name: "page", in: "query", schema: {type: "integer", minimum: 1, default: 1}},
326
+ {name: "per_page", in: "query", description: "Page size, capped at #{sizes}.",
327
+ schema: {type: "integer", minimum: 1, maximum: sizes, default: @static[:default_per_page]}.compact}]
328
+ end
329
+
330
+ def filters = @declared[:filters].reject { Masking.attribute?(it[:name], @config) }
331
+
332
+ def filters_param
333
+ properties = filters.reduce({}) { |all, filter| all.merge(filter_properties(filter)) }
334
+ deep_object("q", properties, description: "Ransack predicates of the declared filters; any other predicate is a 400.") if properties.any?
335
+ end
336
+
337
+ def filter_properties(filter)
338
+ label = filter[:label]
339
+ case filter[:control]
340
+ when "text" then predicates(filter, {type: "string"})
341
+ when "number" then predicates(filter, {type: "number"})
342
+ when "date_range"
343
+ {filter.dig(:range, :from) => {type: "string", format: "date", description: "#{label}, from"},
344
+ filter.dig(:range, :to) => {type: "string", format: "date", description: "#{label}, up to"}}
345
+ when "boolean" then {filter[:param] => {type: "boolean", description: label}}
346
+ else {filter[:param] => choice_filter(filter)}
347
+ end
348
+ end
349
+
350
+ def predicates(filter, type)
351
+ list = filter[:predicates] || [{param: filter[:param], label: nil}]
352
+ list.to_h { [it[:param], {description: [filter[:label], it[:label]].compact.join(" "), **type}] }
353
+ end
354
+
355
+ def choice_filter(filter)
356
+ description = "#{filter[:label]}. Options are served by `GET #{filter[:options_path]}`."
357
+ filter[:multiple] ? {type: "array", items: {type: "string"}, description:} : {type: "string", description:}
358
+ end
359
+
360
+ def scope_param
361
+ scopes = @declared[:scopes]
362
+ return if scopes.empty?
363
+
364
+ default = @declared[:default_scope]
365
+ {name: "scope", in: "query", description: ("Defaults to `#{default}`." if default), schema: {type: "string", enum: scopes.pluck(:id)}}.compact
366
+ end
367
+
368
+ def order_param
369
+ keys = sortable.filter_map { |column, _| column[:sort_key] }.uniq
370
+ return if keys.empty?
371
+
372
+ {name: "order", in: "query", description: "`<sort_key>_asc` or `_desc`; any other key is a 400.", schema: {type: "string", enum: keys.flat_map { ["#{it}_asc", "#{it}_desc"] }}}
373
+ end
374
+
375
+ def views_param
376
+ views = @static[:index_views]
377
+ return unless views
378
+
379
+ {name: "as", in: "query", description: "The index view to render.", schema: {type: "string", enum: views.pluck(:as)}}
380
+ end
381
+
382
+ def sortable = @columns.select { |column, attribute| column[:sortable] && !masked?(attribute) }
383
+
384
+ def masked?(attribute) = attribute && Masking.attribute?(attribute, @config)
385
+
386
+ # Rows
387
+
388
+ def columns_note
389
+ shown = @columns.reject { |_, attribute| masked?(attribute) }
390
+ return "" if shown.empty?
391
+
392
+ "Columns: #{shown.map { |column, _| "#{column[:label]} (`#{column[:key]}`#{", sortable" if column[:sortable]})" }.join(", ")}."
393
+ end
394
+
395
+ def row_schema
396
+ cells = @columns.filter_map { |column, attribute| [column[:key], cell_schema(column, attribute)] unless masked?(attribute) }.to_h
397
+ {allOf: [schema_ref("Row"), {type: "object", properties: {cells: {type: "object", properties: cells}}}]}
398
+ end
399
+
400
+ def cell_schema(column, attribute)
401
+ description = "#{column[:label]}#{" (attribute `#{attribute}`)" if attribute}"
402
+ types = cell_types(attribute)
403
+ return {**schema_ref("Node"), description:} unless types
404
+
405
+ {description:, allOf: [schema_ref("Node"), {properties: {type: {enum: [*types, "empty", "error"]}}}]}
406
+ end
407
+
408
+ # The node types an attribute's value becomes (Values.for); nil where it depends on the host's block.
409
+ def cell_types(attribute)
410
+ return unless attribute
411
+
412
+ klass = @config.resource_class
413
+ reflection = klass.reflect_on_association(attribute)
414
+ return %w[ref text] if reflection && %i[belongs_to has_one].include?(reflection.macro)
415
+ return if reflection
416
+ return %w[ref] if attribute == klass.primary_key
417
+ return %w[text] if klass.defined_enums.key?(attribute)
418
+
419
+ CELL_TYPES[klass.columns_hash[attribute]&.type]
420
+ end
421
+ end
422
+ end
423
+ end
@@ -0,0 +1,55 @@
1
+ module ReactiveAdmin
2
+ module OpenApi
3
+ # The credentials the API takes. By default the host's ActiveAdmin session cookie, plus the CSRF token
4
+ # writes must carry, and a bearer token where `config.auth` has a bearer adapter. Other authentication
5
+ # is declared with `config.openapi.security_schemes`, or by an authorization adapter that defines
6
+ # `openapi_security_scheme`.
7
+ module Security
8
+ SESSION = "sessionCookie".freeze
9
+ CSRF = "csrfToken".freeze
10
+ BEARER = "bearerAuth".freeze
11
+
12
+ module_function
13
+
14
+ def schemes
15
+ configured = ReactiveAdmin.config.openapi.security_schemes || adapter_schemes || defaults
16
+ configured.to_h { |name, scheme| [name.to_s, scheme.deep_stringify_keys] }
17
+ end
18
+
19
+ # A token is an alternative to the session, never an addition: it carries no cookie and no CSRF token.
20
+ def requirement(write:)
21
+ all = schemes
22
+ names = write ? all.keys : all.keys - [CSRF]
23
+ tokens, session = names.partition { token?(all[it]) }
24
+ [session.presence&.to_h { [it, []] }, *tokens.map { {it => []} }].compact
25
+ end
26
+
27
+ # For the endpoints only tokens may call (MCP).
28
+ def token_requirement = schemes.select { |_, scheme| token?(scheme) }.keys.map { {it => []} }
29
+
30
+ def token?(scheme) = %w[oauth2 openIdConnect].include?(scheme["type"]) || (scheme["type"] == "http" && scheme["scheme"].to_s.casecmp?("bearer"))
31
+
32
+ def defaults
33
+ session = Auth.token_only? ? {} : session_schemes
34
+ Auth.bearer? ? session.merge(BEARER => Core.document.dig("components", "securitySchemes", BEARER).symbolize_keys) : session
35
+ end
36
+
37
+ def session_schemes
38
+ {
39
+ SESSION => {type: "apiKey", in: "cookie", name: session_key,
40
+ description: "The signed-in ActiveAdmin session. Sign in to the admin in the same browser; requests carry the cookie."},
41
+ CSRF => {type: "apiKey", in: "header", name: "X-CSRF-Token",
42
+ description: "Required on every write (anything but GET). Read it from `csrf_token` in `GET #{Paths.api("/#{ReactiveAdmin.config.namespace}/_session")}`; a missing or stale token answers 422 `invalid_csrf`."}
43
+ }
44
+ end
45
+
46
+ def adapter_schemes
47
+ adapter = AA.authorization_adapter(Registry.namespace)
48
+ adapter.openapi_security_scheme if adapter.respond_to?(:openapi_security_scheme)
49
+ end
50
+
51
+ # The host's cookie name, when the session store says it.
52
+ def session_key = Rails.application.config.session_options[:key].presence || "_session_id"
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,104 @@
1
+ module ReactiveAdmin
2
+ module OpenApi
3
+ # The JSON body create and update accept, from the same controls-only form schema the runtime
4
+ # judges writes by: each control's `param` is a path into the body (`post[comments_attributes][__INDEX__][body]`).
5
+ # Disabled inputs are dropped by the runtime, and masked ones are left out here, so no credential's name is published.
6
+ class WriteSchema
7
+ # One level of the body: named children, an indexed row template (has_many), or a leaf schema.
8
+ class Node
9
+ attr_accessor :props, :rows, :leaf
10
+
11
+ def initialize(leaf = nil)
12
+ @props = {}
13
+ @leaf = leaf
14
+ end
15
+ end
16
+
17
+ SCALARS = {
18
+ "text" => {type: "string"}, "textarea" => {type: "string"}, "hidden" => {type: "string"}, "select" => {type: "string"},
19
+ "radio" => {type: "string"}, "typeahead" => {type: "string"}, "phone" => {type: "string"},
20
+ "email" => {type: "string", format: "email"}, "url" => {type: "string", format: "uri"},
21
+ "password" => {type: "string", writeOnly: true}, "number" => {type: "number"}, "boolean" => {type: "boolean"},
22
+ "date" => {type: "string", format: "date"}, "datetime" => {type: "string", format: "date-time"},
23
+ "time" => {type: "string", format: "time"},
24
+ "file" => {type: "string", format: "binary", description: "Send the request as multipart/form-data to upload a file."},
25
+ "json" => {"description" => "Structured JSON (object, array or scalar), sent as JSON.", "x-control" => "json"}
26
+ }.freeze
27
+ CHOICES = %w[select radio typeahead multiselect checkboxes].freeze
28
+ INDEX = "__INDEX__".freeze
29
+
30
+ def initialize(config, sections, options_path:, reserved: [])
31
+ @config = config
32
+ @options_path = options_path
33
+ @reserved = reserved
34
+ @root = Node.new
35
+ sections.each { add_section(it) }
36
+ end
37
+
38
+ # The object schema, or nil when the form has no writable control.
39
+ def schema = (render(@root) if @root.props.any?)
40
+
41
+ # Top-level body keys, e.g. the resource's param key.
42
+ def keys = @root.props.keys
43
+
44
+ private
45
+
46
+ def add_section(section)
47
+ if section[:kind] == "has_many"
48
+ add_has_many(section)
49
+ else
50
+ Array(section[:fields]).each { add_field(it) }
51
+ end
52
+ end
53
+
54
+ def add_has_many(section)
55
+ Array(section[:template_fields]).each { add_field(it) }
56
+ return if section[:param].blank? || reserved?(section[:param])
57
+
58
+ row = descend(path_of(section[:param]) + [INDEX])
59
+ row.props["id"] ||= Node.new({type: "string"})
60
+ row.props["_destroy"] ||= Node.new({type: "boolean"}) if section[:allow_destroy]
61
+ end
62
+
63
+ def add_field(field)
64
+ param = field[:param]
65
+ return if param.blank? || field[:disabled] || reserved?(param) || masked?(field[:name])
66
+
67
+ schema = leaf(field, param)
68
+ descend(path_of(param)).leaf = schema if schema
69
+ end
70
+
71
+ # The runtime refuses a write naming a guarded attribute at any depth, so none is published.
72
+ def reserved?(param) = path_of(param).intersect?(@reserved)
73
+
74
+ def masked?(name) = Masking.attribute?(name.to_s.split(".").last, @config)
75
+
76
+ def leaf(field, param)
77
+ control = field[:control]
78
+ base = SCALARS[control]
79
+ base = {type: "array", items: {type: "string"}} if %w[multiselect checkboxes].include?(control)
80
+ return unless base
81
+
82
+ base = {type: "array", items: base} if param.end_with?("[]") && control != "checkboxes" && control != "multiselect"
83
+ hint = "Options are served by `GET #{@options_path}?context=form&field=#{field[:name]}`." if CHOICES.include?(control)
84
+ hint ? {description: hint, **base} : base
85
+ end
86
+
87
+ def path_of(param) = param.scan(/[^\[\]]+/)
88
+
89
+ def descend(path)
90
+ path.inject(@root) do |node, key|
91
+ (key == INDEX) ? (node.rows ||= Node.new) : (node.props[key] ||= Node.new)
92
+ end
93
+ end
94
+
95
+ def render(node)
96
+ return node.leaf if node.leaf
97
+ return {type: "object", additionalProperties: render(node.rows)} if node.rows && node.props.empty?
98
+
99
+ props = node.props.transform_values { render(it) }
100
+ {type: "object", properties: props, additionalProperties: false}
101
+ end
102
+ end
103
+ end
104
+ end