forest_admin_agent 1.45.0 → 1.45.2

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b82038f1c254bc91295ded423735b4f481a3c0b997d4c246d606396ad476acec
4
- data.tar.gz: 8bae29e2cbb6d1af5b9ebf4228a918eaace4b5489e26aa1ba7a098856da3bb38
3
+ metadata.gz: b3d274612ae79795715d531ee72fce9566b2f6bc0ca79fd2f60538498f8cef8e
4
+ data.tar.gz: 54daad3999b1ff2bdcef2257c9638dd2896c160083f852f6e4501cef3288d478
5
5
  SHA512:
6
- metadata.gz: 336ea0d4c27df5a65ed30f6d5e64fd2a4645ae229a9fb874ea21b2c5501cef641c3a18bd91736cb52ed3b0b085dffbe9aa2f17f59471efcf62ab0fcd3ca3dfb4
7
- data.tar.gz: 637d76398dc40a32ec459bb3ae3bdd783c82665a272988185efa1229823639f2cc64b564dbc7be6f1248f31a39f23af241d29bf636d1f48c4b0a7e0306826a55
6
+ metadata.gz: c585bcad5f56d230eeb0dfd382c0a5543bf0a01b97bfee5499ae70e8533055f17b1b1093156ea18daf53ef06fa6daf57c953107da0da94a6461cde8620173f13
7
+ data.tar.gz: 361983398aa5072601e09aea9ddaf75209a9582edc1b28291be9aa144a4c85f512394ea4ef1e40d3449cdb97c39d798ba8564625ee44b7403a1bf99f94218c2d
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2023-2026 Forest Admin
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -12,7 +12,7 @@ Gem::Specification.new do |spec|
12
12
  spec.summary = "Ruby agent for Forest Admin."
13
13
  spec.description = "Forest is a modern admin interface that works on all major web frameworks. This gem makes Forest
14
14
  admin work on any Ruby application."
15
- spec.license = "GPL-3.0"
15
+ spec.license = "Apache-2.0"
16
16
  spec.required_ruby_version = ">= 3.0.0"
17
17
 
18
18
  spec.metadata["homepage_uri"] = spec.homepage
@@ -25,7 +25,7 @@ admin work on any Ruby application."
25
25
  spec.files = Dir.chdir(__dir__) do
26
26
  `git ls-files -z`.split("\x0").reject do |f|
27
27
  (File.expand_path(f) == __FILE__) ||
28
- f.start_with?(*%w[bin/ test/ spec/ .git Gemfile LICENSE])
28
+ f.start_with?(*%w[bin/ test/ spec/ .git Gemfile])
29
29
  end
30
30
  end
31
31
 
@@ -1,4 +1,3 @@
1
- require 'filecache'
2
1
  require 'openid_connect'
3
2
  require_relative 'oauth2/oidc_config'
4
3
  require_relative 'oauth2/forest_provider'
@@ -25,7 +24,7 @@ module ForestAdminAgent
25
24
  private
26
25
 
27
26
  def setup_cache(env_secret, config_agent)
28
- cache = FileCache.new('auth_issuer', (config_agent[:cache_dir]).to_s, TTL)
27
+ cache = ForestAdminAgent::Utils::SafeFileCache.new('auth_issuer', (config_agent[:cache_dir]).to_s, TTL)
29
28
  cache.get_or_set env_secret do
30
29
  oidc_config = retrieve_config(config_agent[:forest_server_url])
31
30
  credentials = register(
@@ -48,11 +48,11 @@ module ForestAdminAgent
48
48
 
49
49
  def handle_request(args = {})
50
50
  context = build(args)
51
+ ensure_served_action(context)
51
52
  args = middleware_custom_action_approval_request_data(args)
52
53
  filter_for_caller = get_record_selection(args, context)
53
- get_record_selection(args, context, include_user_scope: false)
54
54
 
55
- context.permissions.can_smart_action?(args, context.collection, filter_for_caller)
55
+ context.permissions.can_smart_action?(args, context.collection, filter_for_caller, action_name: @action_name)
56
56
 
57
57
  raw_data = args.dig(:params, :data, :attributes, :values)
58
58
 
@@ -82,6 +82,7 @@ module ForestAdminAgent
82
82
 
83
83
  def handle_hook_request(args = {})
84
84
  context = build(args)
85
+ ensure_served_action(context)
85
86
  forest_fields = args.dig(:params, :data, :attributes, :fields)
86
87
  data = (if forest_fields
87
88
  Schema::ForestValueConverter.make_form_data_from_fields(context.datasource,
@@ -117,6 +118,14 @@ module ForestAdminAgent
117
118
 
118
119
  private
119
120
 
121
+ def ensure_served_action(context)
122
+ served_index = @route_collection.schema[:actions].keys.index(@action_name)
123
+ return if context.collection.schema[:actions].keys.index(@action_name) == served_index
124
+
125
+ raise ForestAdminAgent::Http::Exceptions::BadRequestError,
126
+ "The collection #{context.collection.name} does not have this smart action"
127
+ end
128
+
120
129
  # Recorded as pending before the action runs and confirmed after, so an action that takes the process
121
130
  # down with it still leaves evidence that it started. A failed run is worth recording too — "who tried
122
131
  # to run this" is usually the interesting part — and an action answering with an Error result failed
@@ -211,11 +220,11 @@ module ForestAdminAgent
211
220
  )[0])
212
221
  end
213
222
 
214
- def get_record_selection(args, context, include_user_scope: true)
223
+ def get_record_selection(args, context)
215
224
  attributes = args.dig(:params, :data, :attributes)
216
225
 
217
226
  # Match user filter + search + scope? + segment
218
- scope = include_user_scope ? context.permissions.get_scope(context.collection) : nil
227
+ scope = context.permissions.get_scope(context.collection)
219
228
  filter = Filter.new(
220
229
  condition_tree: ConditionTreeFactory.intersect(
221
230
  [
@@ -61,13 +61,14 @@ module ForestAdminAgent
61
61
  def handle_search_decorator(search_value, records, collection)
62
62
  decorator = { decorators: [] }
63
63
  unless search_value.nil?
64
+ search_value = search_value.downcase
64
65
  records.each_with_index do |entry, index|
65
66
  decorator[:decorators][index] = { id: Utils::Id.pack_id(collection, entry), search: [] }
66
67
  # attributes method is defined on ActiveRecord::Base model
67
68
  attributes = entry.respond_to?(:attributes) ? entry.attributes : entry
68
69
 
69
70
  attributes.each do |field_key, field_value|
70
- if !field_value.is_a?(Array) && field_value.to_s.downcase.include?(search_value.downcase)
71
+ if !field_value.is_a?(Array) && field_value.to_s.downcase.include?(search_value)
71
72
  decorator[:decorators][index][:search] << field_key
72
73
  end
73
74
  end
@@ -18,7 +18,8 @@ module ForestAdminAgent
18
18
 
19
19
  def handle_request(args)
20
20
  build(args)
21
- Permissions.invalidate_cache('forest.rendering')
21
+ rendering_id = args.dig(:params, 'renderingId')
22
+ Permissions.invalidate_rendering_cache(rendering_id.to_s.strip.empty? ? nil : rendering_id)
22
23
 
23
24
  { content: nil, status: 204 }
24
25
  end
@@ -5,9 +5,8 @@ module ForestAdminAgent
5
5
  class ForestSerializer
6
6
  include JSONAPI::Serializer
7
7
 
8
- attr_accessor :attributes_map
9
- attr_accessor :to_one_associations
10
- attr_accessor :to_many_associations
8
+ TO_ONE_TYPES = %w[OneToOne ManyToOne PolymorphicManyToOne PolymorphicOneToOne].freeze
9
+ TO_MANY_TYPES = %w[OneToMany ManyToMany PolymorphicOneToMany].freeze
11
10
 
12
11
  JSONAPI::Serializer.send(:include, ForestSerializerOverride)
13
12
 
@@ -26,6 +25,50 @@ module ForestAdminAgent
26
25
 
27
26
  def self.reset_cache!
28
27
  @@primary_keys = {}
28
+ @@layouts = {}.compare_by_identity
29
+ end
30
+
31
+ # Keyed by the collection object, not its name: two datasources can expose a collection under
32
+ # the same name, and the decorator stack returns the same object for a name once built.
33
+ def self.layout_for(collection)
34
+ @@layouts ||= {}.compare_by_identity
35
+ @@layouts[collection] ||= build_layout(collection)
36
+ end
37
+
38
+ def self.build_layout(collection)
39
+ fields = collection.schema[:fields]
40
+ relation = lambda do |types|
41
+ fields.each_with_object({}) do |(name, field), layout|
42
+ next unless types.include?(field.type)
43
+
44
+ layout[name] = { attr_or_block: name, options: { include_links: true, include_data: false }.freeze }.freeze
45
+ end.freeze
46
+ end
47
+
48
+ {
49
+ fields: fields,
50
+ attributes: fields.each_with_object({}) do |(name, field), layout|
51
+ layout[name] = { attr_or_block: name, options: {}.freeze }.freeze if field.type == 'Column'
52
+ end.freeze,
53
+ to_one: relation.call(TO_ONE_TYPES),
54
+ to_many: relation.call(TO_MANY_TYPES)
55
+ }.freeze
56
+ end
57
+
58
+ def layout
59
+ @layout ||= self.class.layout_for(ForestAdminAgent::Facades::Container.datasource.get_collection(type))
60
+ end
61
+
62
+ def attributes_map
63
+ layout[:attributes]
64
+ end
65
+
66
+ def to_one_associations
67
+ layout[:to_one]
68
+ end
69
+
70
+ def to_many_associations
71
+ layout[:to_many]
29
72
  end
30
73
 
31
74
  def id
@@ -40,25 +83,7 @@ module ForestAdminAgent
40
83
  attribute_name.to_s
41
84
  end
42
85
 
43
- def add_attribute(name, options = {}, &block)
44
- @attributes_map ||= {}
45
- @attributes_map[name] = format_field(name, options)
46
- end
47
-
48
- def format_field(name, options)
49
- {
50
- attr_or_block: block_given? ? block : name,
51
- options: options,
52
- }
53
- end
54
-
55
86
  def attributes
56
- forest_collection = ForestAdminAgent::Facades::Container.datasource.get_collection(
57
- @options[:class_name].gsub('::', '__')
58
- )
59
- fields = forest_collection.schema[:fields].select { |_field_name, field| field.type == 'Column' }
60
- fields.each { |field_name, _field| add_attribute(field_name) }
61
- return {} if attributes_map.nil?
62
87
  attributes = {}
63
88
 
64
89
  attributes_map.each do |attribute_name, attr_data|
@@ -86,22 +111,13 @@ module ForestAdminAgent
86
111
  end
87
112
  end
88
113
 
89
- def add_to_one_association(name, options = {}, &block)
90
- options[:include_links] = options.fetch(:include_links, true)
91
- options[:include_data] = options.fetch(:include_data, false)
92
- @to_one_associations ||= {}
93
- @to_one_associations[name] = format_field(name, options)
94
- end
95
-
96
114
  # A PolymorphicManyToOne can't be SQL-joined, so list projections return a phantom object with no
97
115
  # primary key. Rebuild the id from the foreign key on the owner record.
98
116
  def has_one_relationship(attribute_name, attr_data)
99
117
  object = super
100
118
  return object if object.nil? # relation not projected (e.g. update/store responses)
101
119
 
102
- field = ForestAdminAgent::Facades::Container.datasource
103
- .get_collection(@options[:class_name].gsub('::', '__'))
104
- .schema[:fields][attribute_name.to_s]
120
+ field = layout[:fields][attribute_name.to_s]
105
121
  return object unless field&.type == 'PolymorphicManyToOne'
106
122
 
107
123
  foreign_key = @object[field.foreign_key]
@@ -115,9 +131,8 @@ module ForestAdminAgent
115
131
  end
116
132
 
117
133
  def has_one_relationships
118
- return {} if @to_one_associations.nil?
119
134
  data = {}
120
- @to_one_associations.each do |attribute_name, attr_data|
135
+ to_one_associations.each do |attribute_name, attr_data|
121
136
  next if !should_include_attr?(attribute_name, attr_data)
122
137
  data[attribute_name.to_sym] = attr_data
123
138
  end
@@ -125,34 +140,16 @@ module ForestAdminAgent
125
140
  end
126
141
 
127
142
  def has_many_relationships
128
- return {} if @to_many_associations.nil?
129
143
  data = {}
130
- @to_many_associations.each do |attribute_name, attr_data|
144
+ to_many_associations.each do |attribute_name, attr_data|
131
145
  next if !should_include_attr?(attribute_name, attr_data)
132
146
  data[attribute_name.to_sym] = attr_data
133
147
  end
134
148
  data
135
149
  end
136
150
 
137
- def add_to_many_association(name, options = {}, &block)
138
- options[:include_links] = options.fetch(:include_links, true)
139
- options[:include_data] = options.fetch(:include_data, false)
140
- @to_many_associations ||= {}
141
- @to_many_associations[name] = format_field(name, options)
142
- end
143
-
144
151
  def relationships
145
152
  datasource = ForestAdminAgent::Facades::Container.datasource
146
- forest_collection = datasource.get_collection(@options[:class_name].gsub('::', '__'))
147
- relations_to_many = forest_collection.schema[:fields].select do |_field_name, field|
148
- %w[OneToMany ManyToMany PolymorphicOneToMany].include?(field.type)
149
- end
150
- relations_to_one = forest_collection.schema[:fields].select do |_field_name, field|
151
- %w[OneToOne ManyToOne PolymorphicManyToOne PolymorphicOneToOne].include?(field.type)
152
- end
153
-
154
- relations_to_one.each { |field_name, _field| add_to_one_association(field_name) }
155
-
156
153
  data = {}
157
154
  has_one_relationships.each do |attribute_name, attr_data|
158
155
  formatted_attribute_name = format_name(attribute_name)
@@ -170,8 +167,7 @@ module ForestAdminAgent
170
167
  # Only include 'data' key if the relationship object exists
171
168
  # Omit 'data' key entirely when null instead of setting it to null
172
169
  unless object.nil? || (object.respond_to?(:empty?) && object.empty?)
173
- relation = datasource.get_collection(@options[:class_name].gsub('::', '__'))
174
- .schema[:fields][attribute_name.to_s]
170
+ relation = layout[:fields][attribute_name.to_s]
175
171
  options = @options.clone
176
172
  if relation.type == 'PolymorphicManyToOne'
177
173
  options[:class_name] = @object[relation.foreign_key_type_field]
@@ -191,8 +187,6 @@ module ForestAdminAgent
191
187
  end
192
188
  end
193
189
 
194
- relations_to_many.each { |field_name, _field| add_to_many_association(field_name) }
195
-
196
190
  has_many_relationships.each do |attribute_name, attr_data|
197
191
  formatted_attribute_name = format_name(attribute_name)
198
192
  data[formatted_attribute_name] = {}
@@ -208,7 +202,7 @@ module ForestAdminAgent
208
202
  if @_include_linkages.include?(formatted_attribute_name) || attr_data[:options][:include_data]
209
203
  data[formatted_attribute_name]['data'] = []
210
204
  objects = has_many_relationship(attribute_name, attr_data) || []
211
- relation = datasource.get_collection(@options[:class_name].gsub('::', '__')).schema[:fields][attribute_name.to_s]
205
+ relation = layout[:fields][attribute_name.to_s]
212
206
  options = @options.clone
213
207
  options[:class_name] = datasource.get_collection(relation.foreign_collection).name
214
208
  objects.each do |obj|
@@ -17,7 +17,6 @@ module ForestAdminAgent
17
17
  next if attribute_name == :_include
18
18
 
19
19
  serializer = JSONAPI::Serializer.find_serializer(root_object, options)
20
- serializer.relationships
21
20
  unformatted_attr_name = serializer.unformat_name(attribute_name).to_sym
22
21
 
23
22
  # We know the name of this relationship, but we don't know where it is stored internally.
@@ -55,9 +54,7 @@ module ForestAdminAgent
55
54
  # in the response.
56
55
  objects = is_collection ? object : [object]
57
56
 
58
- relation = ForestAdminAgent::Facades::Container.datasource
59
- .get_collection(options[:class_name].gsub('::', '__'))
60
- .schema[:fields][attribute_name]
57
+ relation = serializer.layout[:fields][attribute_name]
61
58
  if relation.type == 'PolymorphicManyToOne'
62
59
  relation_class_name = root_object[relation.foreign_key_type_field]
63
60
  else
@@ -1,5 +1,4 @@
1
1
  require 'ipaddress'
2
- require 'filecache'
3
2
  require 'json'
4
3
 
5
4
  module ForestAdminAgent
@@ -14,7 +13,11 @@ module ForestAdminAgent
14
13
 
15
14
  def initialize
16
15
  @forest_api = ForestAdminAgent::Http::ForestAdminApiRequester.new
17
- @cache = FileCache.new(
16
+ @cache = self.class.build_cache
17
+ end
18
+
19
+ def self.build_cache
20
+ ForestAdminAgent::Utils::SafeFileCache.new(
18
21
  'ip_whitelist',
19
22
  Facades::Container.config_from_cache[:cache_dir].to_s,
20
23
  Facades::Container.config_from_cache[:permission_expiration]
@@ -22,12 +25,7 @@ module ForestAdminAgent
22
25
  end
23
26
 
24
27
  def self.invalidate_cache
25
- cache = FileCache.new(
26
- 'ip_whitelist',
27
- Facades::Container.config_from_cache[:cache_dir].to_s,
28
- Facades::Container.config_from_cache[:permission_expiration]
29
- )
30
- cache.delete(CACHE_KEY) unless cache.get(CACHE_KEY).nil?
28
+ build_cache.delete(CACHE_KEY)
31
29
  end
32
30
 
33
31
  def use_ip_whitelist
@@ -1,4 +1,3 @@
1
- require 'filecache'
2
1
  require 'deepsort'
3
2
 
4
3
  module ForestAdminAgent
@@ -10,6 +9,9 @@ module ForestAdminAgent
10
9
  include ForestAdminDatasourceToolkit::Components::Query::ConditionTree
11
10
 
12
11
  USERS_RELOAD_INTERVAL_IN_SECONDS = 60
12
+ # Renderings live in their own domain because FileCache cannot delete by key prefix: clearing
13
+ # the domain is the only way to drop every rendering when the server does not say which one.
14
+ RENDERINGS_CACHE_DOMAIN = 'permissions-renderings'.freeze
13
15
 
14
16
  @users_reload_mutex = Mutex.new
15
17
 
@@ -18,30 +20,49 @@ module ForestAdminAgent
18
20
  def initialize(caller)
19
21
  @caller = caller
20
22
  @forest_api = ForestAdminAgent::Http::ForestAdminApiRequester.new
21
- @cache = FileCache.new(
22
- 'permissions',
23
+ @cache = self.class.build_cache('permissions')
24
+ @memo = {}
25
+ end
26
+
27
+ def rendering_cache
28
+ @rendering_cache ||= self.class.build_cache(RENDERINGS_CACHE_DOMAIN)
29
+ end
30
+
31
+ def self.build_cache(domain)
32
+ ForestAdminAgent::Utils::SafeFileCache.new(
33
+ domain,
23
34
  Facades::Container.config_from_cache[:cache_dir].to_s,
24
35
  Facades::Container.config_from_cache[:permission_expiration]
25
36
  )
26
37
  end
27
38
 
28
39
  def self.invalidate_cache(id_cache = nil)
29
- cache = FileCache.new(
30
- 'permissions',
31
- Facades::Container.config_from_cache[:cache_dir].to_s,
32
- Facades::Container.config_from_cache[:permission_expiration]
33
- )
40
+ cache = build_cache('permissions')
34
41
 
35
42
  if id_cache.nil?
36
43
  cache.clear
44
+ build_cache(RENDERINGS_CACHE_DOMAIN).clear
37
45
  @users_reload_mutex.synchronize { @users_reloaded_at = nil }
38
46
  end
39
47
 
40
- cache.delete(id_cache) unless cache.get(id_cache).nil?
48
+ cache.delete(id_cache)
41
49
 
42
50
  ForestAdminAgent::Facades::Container.logger.log('Info', "Invalidating #{id_cache} cache..")
43
51
  end
44
52
 
53
+ def self.invalidate_rendering_cache(rendering_id = nil)
54
+ cache = build_cache(RENDERINGS_CACHE_DOMAIN)
55
+
56
+ if rendering_id.nil?
57
+ cache.clear
58
+ else
59
+ cache.delete(rendering_id.to_s)
60
+ end
61
+
62
+ target = rendering_id.nil? ? 'every rendering' : "rendering #{rendering_id}"
63
+ ForestAdminAgent::Facades::Container.logger.log('Info', "Invalidating #{target} permissions cache..")
64
+ end
65
+
45
66
  def self.users_reload_allowed?
46
67
  @users_reload_mutex.synchronize do
47
68
  now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
@@ -210,20 +231,19 @@ module ForestAdminAgent
210
231
  is_allowed
211
232
  end
212
233
 
213
- def can_smart_action?(request, collection, filter, allow_fetch: true)
234
+ def can_smart_action?(request, collection, filter, action_name:, allow_fetch: true)
214
235
  return true unless permission_system?
215
236
 
216
237
  user_data = get_user_data(caller.id)
217
238
  collections_data = get_collections_permissions_data(force_fetch: allow_fetch)
218
- action = find_action_from_endpoint(collection.name, request[:headers]['REQUEST_PATH'], request[:headers]['REQUEST_METHOD'])
219
239
 
220
- collection_actions = validate_smart_action_permissions(collections_data, collection, action)
240
+ collection_actions = validate_smart_action_permissions(collections_data, collection, action_name)
221
241
 
222
242
  smart_action_approval = SmartActionChecker.new(
223
243
  request[:params],
224
244
  collection,
225
245
  # The schema scope lets the checker skip select-all resolution for global actions.
226
- collection_actions[action['name'].to_sym].merge(scope: collection.schema[:actions][action['name']]&.scope),
246
+ collection_actions[action_name.to_sym].merge(scope: collection.schema[:actions][action_name]&.scope),
227
247
  caller,
228
248
  user_data[:roleId],
229
249
  filter
@@ -232,7 +252,7 @@ module ForestAdminAgent
232
252
  is_allowed = smart_action_approval.can_execute?
233
253
  ForestAdminAgent::Facades::Container.logger.log(
234
254
  'Debug',
235
- "User #{user_data[:roleId]} is #{"not" unless is_allowed} allowed to perform #{action["name"]}"
255
+ "User #{user_data[:roleId]} is #{"not" unless is_allowed} allowed to perform #{action_name}"
236
256
  )
237
257
 
238
258
  is_allowed
@@ -279,8 +299,16 @@ module ForestAdminAgent
279
299
 
280
300
  private
281
301
 
302
+ def cached(store, key, &fetch)
303
+ @memo.fetch([store, key]) { @memo[[store, key]] = store.get_or_set(key, &fetch) }
304
+ end
305
+
306
+ def forget(store, key)
307
+ @memo.delete([store, key])
308
+ end
309
+
282
310
  def cached_users
283
- cache.get_or_set('forest.users') do
311
+ cached(cache, 'forest.users') do
284
312
  response = fetch('/liana/v4/permissions/users')
285
313
  users = {}
286
314
 
@@ -295,9 +323,8 @@ module ForestAdminAgent
295
323
  end
296
324
 
297
325
  def reload_users
298
- return cached_users unless self.class.users_reload_allowed?
299
-
300
- self.class.invalidate_cache('forest.users')
326
+ self.class.invalidate_cache('forest.users') if self.class.users_reload_allowed?
327
+ forget(cache, 'forest.users')
301
328
  cached_users
302
329
  end
303
330
 
@@ -442,9 +469,12 @@ module ForestAdminAgent
442
469
  end
443
470
 
444
471
  def get_collections_permissions_data(force_fetch: false)
445
- self.class.invalidate_cache('forest.collections') if force_fetch == true
472
+ if force_fetch == true
473
+ self.class.invalidate_cache('forest.collections')
474
+ forget(cache, 'forest.collections')
475
+ end
446
476
 
447
- cache.get_or_set('forest.collections') do
477
+ cached(cache, 'forest.collections') do
448
478
  response = fetch('/liana/v4/permissions/environment')
449
479
  collections = {}
450
480
 
@@ -484,9 +514,12 @@ module ForestAdminAgent
484
514
  end
485
515
 
486
516
  def get_rendering_data(rendering_id, force_fetch: false)
487
- self.class.invalidate_cache('forest.rendering') if force_fetch == true
517
+ if force_fetch == true
518
+ self.class.invalidate_rendering_cache(rendering_id)
519
+ forget(rendering_cache, rendering_id.to_s)
520
+ end
488
521
 
489
- cache.get_or_set('forest.rendering') do
522
+ cached(rendering_cache, rendering_id.to_s) do
490
523
  data = {}
491
524
  response = fetch("/liana/v4/permissions/renderings/#{rendering_id}")
492
525
 
@@ -501,26 +534,12 @@ module ForestAdminAgent
501
534
  end
502
535
 
503
536
  def permission_system?
504
- cache.get_or_set('forest.has_permission') do
537
+ cached(cache, 'forest.has_permission') do
505
538
  response = fetch('/liana/v4/permissions/environment')
506
539
  { enable: response != true }
507
540
  end[:enable]
508
541
  end
509
542
 
510
- def find_action_from_endpoint(collection_name, path, http_method)
511
- endpoint = path.partition('/forest/')[1..].join
512
- schema_file = JSON.parse(File.read(Facades::Container.config_from_cache[:schema_path]))
513
- actions = schema_file['collections']&.find { |collection| collection['name'] == collection_name }&.dig('actions')
514
-
515
- return nil if actions.nil? || actions.empty?
516
-
517
- action = actions.find { |a| a['endpoint'] == endpoint && a['httpMethod'].casecmp(http_method).zero? }
518
-
519
- raise BadRequestError, "The collection #{collection_name} does not have this smart action" if action.nil?
520
-
521
- action
522
- end
523
-
524
543
  def decode_crud_permissions(collection)
525
544
  unless collection.is_a?(Hash) && collection.key?(:collection)
526
545
  ForestAdminAgent::Facades::Container.logger.log(
@@ -693,7 +712,7 @@ module ForestAdminAgent
693
712
  has_permission
694
713
  end
695
714
 
696
- def validate_smart_action_permissions(collections_data, collection, action)
715
+ def validate_smart_action_permissions(collections_data, collection, action_name)
697
716
  collection_key = collection.name.to_sym
698
717
 
699
718
  unless collections_data.key?(collection_key)
@@ -713,13 +732,13 @@ module ForestAdminAgent
713
732
  raise ForbiddenError, "No actions configured for collection '#{collection.name}'"
714
733
  end
715
734
 
716
- action_key = action['name'].to_sym
735
+ action_key = action_name.to_sym
717
736
  unless collection_actions.key?(action_key)
718
737
  ForestAdminAgent::Facades::Container.logger.log(
719
738
  'Warn',
720
- "Smart action '#{action["name"]}' not found in permissions for collection '#{collection.name}'"
739
+ "Smart action '#{action_name}' not found in permissions for collection '#{collection.name}'"
721
740
  )
722
- raise ForbiddenError, "Smart action '#{action["name"]}' is not configured"
741
+ raise ForbiddenError, "Smart action '#{action_name}' is not configured"
723
742
  end
724
743
 
725
744
  collection_actions
@@ -9,7 +9,7 @@ module ForestAdminAgent
9
9
  MESSAGE_CACHE_KEYS = {
10
10
  'refresh-users': %w[forest.users],
11
11
  'refresh-roles': %w[forest.collections],
12
- 'refresh-renderings': %w[forest.collections forest.rendering]
12
+ 'refresh-renderings': %w[forest.collections]
13
13
  # TODO: add one for ip whitelist when server implement it
14
14
  }.freeze
15
15
 
@@ -32,6 +32,7 @@ module ForestAdminAgent
32
32
  "invalidate cache #{MESSAGE_CACHE_KEYS[event.type]} for event #{event.type}"
33
33
  )
34
34
  end
35
+ invalidate_renderings(event.data) if event.type == :'refresh-renderings'
35
36
 
36
37
  ForestAdminAgent::Facades::Container.logger.log(
37
38
  'Info',
@@ -57,6 +58,23 @@ module ForestAdminAgent
57
58
  )
58
59
  end
59
60
  end
61
+
62
+ # An event that does not name its renderings could concern any of them, so all are dropped.
63
+ def self.invalidate_renderings(data)
64
+ rendering_ids = begin
65
+ parsed = JSON.parse(data.to_s)
66
+ parsed['renderingIds'] if parsed.is_a?(Hash)
67
+ rescue JSON::ParserError
68
+ nil
69
+ end
70
+
71
+ if rendering_ids.is_a?(Array) && rendering_ids.any?
72
+ rendering_ids.each { |rendering_id| Permissions.invalidate_rendering_cache(rendering_id) }
73
+ else
74
+ Permissions.invalidate_rendering_cache
75
+ end
76
+ end
77
+ private_class_method :invalidate_renderings
60
78
  end
61
79
  end
62
80
  end
@@ -0,0 +1,52 @@
1
+ require 'filecache'
2
+ require 'securerandom'
3
+
4
+ module ForestAdminAgent
5
+ module Utils
6
+ # Same on-disk layout as FileCache, so processes running either version share one cache.
7
+ class SafeFileCache < FileCache
8
+ def get(key)
9
+ path = path_for(key)
10
+ return nil if expired?(path)
11
+
12
+ File.open(path, 'rb') { |file| Marshal.load(file) } # rubocop:disable Security/MarshalLoad
13
+ rescue Errno::ENOENT, ArgumentError, TypeError, EOFError
14
+ nil
15
+ end
16
+
17
+ def set(key, value)
18
+ path = path_for(key)
19
+ FileUtils.mkdir_p(File.dirname(path))
20
+ temp_path = File.join(File.dirname(path), ".#{File.basename(path)}.#{Process.pid}.#{SecureRandom.hex(4)}")
21
+
22
+ File.open(temp_path, 'wb') { |file| Marshal.dump(value, file) }
23
+ File.rename(temp_path, path)
24
+ rescue Errno::ENOENT
25
+ nil
26
+ ensure
27
+ FileUtils.rm_f(temp_path) if temp_path
28
+ end
29
+
30
+ def delete(key)
31
+ FileUtils.rm_f(path_for(key))
32
+ end
33
+
34
+ def clear
35
+ FileUtils.rm_rf(get_root)
36
+ FileUtils.mkdir_p(get_root)
37
+ end
38
+
39
+ private
40
+
41
+ def path_for(key)
42
+ md5 = Digest::MD5.hexdigest(key.to_s)
43
+
44
+ File.join(get_root, *md5[0...@depth].chars, md5)
45
+ end
46
+
47
+ def expired?(path)
48
+ @expiry.positive? && Time.now - File.mtime(path) >= @expiry
49
+ end
50
+ end
51
+ end
52
+ end
@@ -6,7 +6,7 @@ module ForestAdminAgent
6
6
  module Schema
7
7
  class SchemaEmitter
8
8
  LIANA_NAME = "agent-ruby"
9
- LIANA_VERSION = "1.45.0"
9
+ LIANA_VERSION = "1.45.2"
10
10
 
11
11
  def self.generate(datasource)
12
12
  datasource.collections
@@ -1,3 +1,3 @@
1
1
  module ForestAdminAgent
2
- VERSION = "1.45.0"
2
+ VERSION = "1.45.2"
3
3
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: forest_admin_agent
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.45.0
4
+ version: 1.45.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Matthieu
@@ -9,7 +9,7 @@ authors:
9
9
  autorequire:
10
10
  bindir: exe
11
11
  cert_chain: []
12
- date: 2026-10-07 00:00:00.000000000 Z
12
+ date: 2026-10-14 00:00:00.000000000 Z
13
13
  dependencies:
14
14
  - !ruby/object:Gem::Dependency
15
15
  name: activesupport
@@ -331,6 +331,7 @@ extra_rdoc_files: []
331
331
  files:
332
332
  - ".rspec"
333
333
  - AUDIT_TRAIL.md
334
+ - LICENSE
334
335
  - Rakefile
335
336
  - forest_admin
336
337
  - forest_admin_agent.gemspec
@@ -418,6 +419,7 @@ files:
418
419
  - lib/forest_admin_agent/utils/is_segment_query_allowed_on_connection.rb
419
420
  - lib/forest_admin_agent/utils/query_string_parser.rb
420
421
  - lib/forest_admin_agent/utils/query_validator.rb
422
+ - lib/forest_admin_agent/utils/safe_file_cache.rb
421
423
  - lib/forest_admin_agent/utils/schema/action_fields.rb
422
424
  - lib/forest_admin_agent/utils/schema/forest_value_converter.rb
423
425
  - lib/forest_admin_agent/utils/schema/frontend_filterable.rb
@@ -440,7 +442,7 @@ files:
440
442
  - sig/forest_admin_agent/routes/system/health_check.rbs
441
443
  homepage: https://www.forestadmin.com
442
444
  licenses:
443
- - GPL-3.0
445
+ - Apache-2.0
444
446
  metadata:
445
447
  homepage_uri: https://www.forestadmin.com
446
448
  source_code_uri: https://github.com/ForestAdmin/agent-ruby