model_driven_api 3.17.0 → 3.18.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 8ab0bcc6554cbf9711eeb67df0e7cc996f187527bd3ea7393ad3d42e4f6107f3
4
- data.tar.gz: 6d4bdb9d4be44078ae4a69cd65456a1d22cf4e5727783d02bcef333d2c5ba770
3
+ metadata.gz: b18e677036c14852dba06410da79ef19389baa005b05581cbe7e7666744622b1
4
+ data.tar.gz: bbf43b381479c8de9dc7c755074ba1b8291305bbd57c6f1196307fe9b34f8b3f
5
5
  SHA512:
6
- metadata.gz: fe1733f08abafc143a01d67ca0b18ff293fb8411085d2fd57bb2383725c0a8f9bda5a78fd74a6e9d94afe87f2f5bc85eceaa2f6ca1d88637377f0aa169b7c6ae
7
- data.tar.gz: c6775bc6268cfa95904339251e469dc3ba41829d9e9d75a457ecb2d2dbec9e1a4319c8bb0a7e3a67a94733ce86d331477ffb723a524bf516978a22ebf102cf7b
6
+ metadata.gz: 6a1ed69d37339dadd60a593d907ecd2ddac9e819dee7fb9f5959762e3ecc9571fccc0bb60e673aca149f6966fc6bedbde9d406169f5be739dd752784cb058a42
7
+ data.tar.gz: 571015de06d02774a28a5efb46ed0cc5a1ec322df33da33383d5883de307f79db2d996a485330282d79e330caf9b4cc94983929b0fe81572e3e7209b199589fb
data/README.md CHANGED
@@ -195,6 +195,8 @@ Parameters work identically in query string (GET) and JSON body (POST search).
195
195
  }
196
196
  ```
197
197
 
198
+ The client's options follow conventions (ADR 0006): `include` takes real associations only; secrets the model hides by default (e.g. Devise's `encrypted_password`) never come back; `methods` serves what the model declares in `json_attrs[:methods]`, columns, associations, `<association>_ids`, and public methods written in the app or a thecore gem (not ending in `!`/`=`, no required arguments), which run read-only. Anything else is dropped from the response and logged; the response stays 200.
199
+
198
200
  #### Ransack filtering (`q`)
199
201
 
200
202
  ```
@@ -273,9 +273,11 @@ class Api::V2::ApplicationController < ActionController::API
273
273
  # In order of importance: if you send the configuration via querystring you are ok
274
274
  # has precedence over if you have setup the json_attrs in the model concern
275
275
  # (JSON_ATTRS_PARAMS order: json_attrs wins over a; reject_non_hash_json_attrs ran first).
276
+ # Options from the request follow the conventions of Api::V2::RequestJsonAttrs (host Odoo #6285).
276
277
  from_params = nil
277
278
  JSON_ATTRS_PARAMS.each { |key| from_params = params[key].deep_symbolize_keys if params[key].present? }
278
- from_params.presence || @json_attrs.presence || @model.json_attrs.presence || {} rescue {}
279
+ return Api::V2::RequestJsonAttrs.from_params(from_params) if from_params.present?
280
+ @json_attrs.presence || @model.json_attrs.presence || {} rescue {}
279
281
  end
280
282
 
281
283
  def extract_model
@@ -27,6 +27,17 @@ module AutoIncludeJson
27
27
  end
28
28
  end
29
29
 
30
+ # What to preload and the options to serialize with. Options from the request (a / json_attrs)
31
+ # preload only real associations of +klass+ and keep their marks (Api::V2::RequestJsonAttrs);
32
+ # the code's own options go through build_includes / sanitize_includes as before.
33
+ def includes_and_options(klass, options)
34
+ if Api::V2::RequestJsonAttrs.marked?(options)
35
+ [Api::V2::RequestJsonAttrs.preloads(klass, options[:include]), options]
36
+ else
37
+ [build_includes(options[:include]), options.merge(include: sanitize_includes(options[:include]))]
38
+ end
39
+ end
40
+
30
41
  # Recursively sanitize include options to ensure only, except, methods propagate
31
42
  def sanitize_includes(include_option)
32
43
  case include_option
@@ -60,9 +71,7 @@ module AutoIncludeRelationJson
60
71
  Rails.logger.debug "AutoIncludeJson - Relation JSON to_json from #{caller_locations(1,1).first.label}"
61
72
  return super unless options.is_a?(Hash) && options[:include]
62
73
 
63
- includes_hash = build_includes(options[:include])
64
- sanitized_includes = sanitize_includes(options[:include])
65
- options = options.merge(include: sanitized_includes)
74
+ includes_hash, options = includes_and_options(klass, options)
66
75
 
67
76
  self.includes(includes_hash).load.to_a.to_json(options)
68
77
  end
@@ -71,9 +80,7 @@ module AutoIncludeRelationJson
71
80
  Rails.logger.debug "AutoIncludeJson - Relation JSON as_json from #{caller_locations(1,1).first.label}"
72
81
  return super unless options.is_a?(Hash) && options[:include]
73
82
 
74
- includes_hash = build_includes(options[:include])
75
- sanitized_includes = sanitize_includes(options[:include])
76
- options = options.merge(include: sanitized_includes)
83
+ includes_hash, options = includes_and_options(klass, options)
77
84
 
78
85
  self.includes(includes_hash).load.to_a.as_json(options)
79
86
  end
@@ -99,15 +106,14 @@ module AutoIncludeInstanceJson
99
106
  Rails.logger.debug "AutoIncludeJson - Instance JSON preload_and_sanitize from #{caller_locations(1,1).first.label}"
100
107
  return options unless options.is_a?(Hash) && options[:include]
101
108
 
102
- includes_hash = build_includes(options[:include])
103
- sanitized_includes = sanitize_includes(options[:include])
109
+ includes_hash, options = includes_and_options(self.class, options)
104
110
 
105
111
  ActiveRecord::Associations::Preloader.new(
106
112
  records: [self],
107
113
  associations: includes_hash
108
114
  ).call
109
115
 
110
- options.merge(include: sanitized_includes)
116
+ options
111
117
  end
112
118
 
113
119
  end
@@ -0,0 +1,5 @@
1
+ # Serialization options sent by the client (a / json_attrs) follow the conventions of
2
+ # Api::V2::RequestJsonAttrs (host Odoo #6285); options built by the code are untouched.
3
+ # Prepended to the module (Ruby >= 3.0 reaches the classes that already include it): records and
4
+ # the ActiveModel objects a custom action returns.
5
+ ActiveModel::Serialization.prepend(Api::V2::RequestJsonAttrs::Serialization)
@@ -0,0 +1,215 @@
1
+ module Api
2
+ module V2
3
+ # Serialization options a client sends in the query string (`a`, alias `json_attrs`) replace the
4
+ # model's own json_attrs, and Rails runs `send` on every `methods` name and `include` key. These
5
+ # options follow conventions instead of lists (ADR 0006, host Odoo #6285):
6
+ #
7
+ # - `include` keeps only real associations of each record's class;
8
+ # - attributes the class hides by default (column_names minus a new record's default
9
+ # serializable_hash, e.g. Devise's encrypted_password, LdapServer#admin_password) never come back;
10
+ # - a `methods` name declared in the class's json_attrs[:methods] runs as before (a developer
11
+ # exposed it); a column or association reader (or `<assoc>_ids`) is a plain read; any other
12
+ # name must be public, end in neither `!` nor `=`, take no required argument and be written in
13
+ # the host or in a thecore gem (a gem named thecore* or depending on one), and it runs under
14
+ # the read-only guard: if it writes, or raises, only that field is dropped.
15
+ #
16
+ # A dropped name is logged once per request and the response stays 200. Options built by the
17
+ # code (a model's json_attrs, a custom action's @json_attrs) carry no MARK and are untouched.
18
+ module RequestJsonAttrs
19
+ MARK = :_from_request
20
+
21
+ module_function
22
+
23
+ # The client's options, with MARK at every level the serializer will read.
24
+ def from_params(options)
25
+ mark(options.deep_symbolize_keys)
26
+ end
27
+
28
+ def mark(options)
29
+ options = options.merge(MARK => true)
30
+ includes = normalize_includes(options[:include])
31
+ options[:include] = includes.transform_values { |nested| mark(nested) } if options.key?(:include)
32
+ options
33
+ end
34
+
35
+ def marked?(options)
36
+ options.is_a?(Hash) && options[MARK]
37
+ end
38
+
39
+ # `include` as { assoc => options }, whatever form the client sent (symbol, string, array,
40
+ # hash). Not ResourceAttributeSet#parsed_includes: that one reads the model's own json_attrs
41
+ # (symbols, nil specs); request params arrive as strings and must come out as option hashes.
42
+ def normalize_includes(include_option)
43
+ case include_option
44
+ when Hash then include_option.to_h { |k, v| [k.to_sym, v.is_a?(Hash) ? v.deep_symbolize_keys : {}] }
45
+ when Array then include_option.each_with_object({}) { |i, h| h.merge!(normalize_includes(i)) }
46
+ when String, Symbol then {include_option.to_sym => {}}
47
+ else {}
48
+ end
49
+ end
50
+
51
+ # The options Rails should serialize a record of +klass+ with, and the methods to evaluate
52
+ # under the read-only guard.
53
+ def for_class(klass, options)
54
+ hidden = hidden_attributes(klass)
55
+ rewritten = options.except(MARK)
56
+ rewritten[:only] = Array(options[:only]).map(&:to_s) - hidden if options.key?(:only)
57
+ rewritten[:except] = Array(options[:except]).map(&:to_s) | hidden
58
+ if options.key?(:include)
59
+ rewritten[:include] = normalize_includes(options[:include]).select do |name, _|
60
+ next true if active_record?(klass) && klass.reflect_on_association(name)
61
+
62
+ drop(klass, name, "not an association")
63
+ false
64
+ end
65
+ end
66
+ plain, guarded = [], []
67
+ Array(options[:methods]).map(&:to_s).uniq.each do |name|
68
+ case (kind = method_kind(klass, name))
69
+ when :declared, :reader then plain << name
70
+ when :guarded then guarded << name
71
+ else drop(klass, name, kind)
72
+ end
73
+ end
74
+ rewritten[:methods] = plain
75
+ [rewritten, guarded]
76
+ end
77
+
78
+ # :declared, :reader, :guarded, or the reason it is refused (a String). Cached per class and
79
+ # name, but only for names the class defines: the client chooses the names, so caching any
80
+ # name would let it grow memory without bound.
81
+ def method_kind(klass, name)
82
+ return "not a public method" unless klass.method_defined?(name) || klass.private_method_defined?(name)
83
+
84
+ (@method_kinds ||= Concurrent::Map.new).compute_if_absent([klass, name]) { classify(klass, name) }
85
+ end
86
+
87
+ def classify(klass, name)
88
+ return "hidden attribute" if hidden_attributes(klass).include?(name)
89
+ return :declared if declared_methods(klass).include?(name)
90
+ return :reader if reader?(klass, name)
91
+ return "ends in ! or =" if name.end_with?("!", "=")
92
+ return "not a public method" unless klass.public_method_defined?(name)
93
+
94
+ method = klass.instance_method(name)
95
+ return "takes required arguments" if method.parameters.any? { |type, _| %i[req keyreq].include?(type) }
96
+ return "not written in the app or a thecore gem" unless our_code?(method.source_location&.first)
97
+
98
+ :guarded
99
+ end
100
+
101
+ def declared_methods(klass)
102
+ return [] unless klass.respond_to?(:json_attrs) && klass.json_attrs.is_a?(Hash)
103
+
104
+ Api::ResourceAttributeSet.for(klass).methods_list.map(&:to_s)
105
+ end
106
+
107
+ def active_record?(klass) = klass < ActiveRecord::Base
108
+
109
+ def reader?(klass, name)
110
+ return false unless active_record?(klass)
111
+ return true if klass.column_names.include?(name)
112
+ return true if klass.reflect_on_association(name)
113
+
114
+ klass.reflect_on_all_associations.any? { |r| r.collection? && "#{r.name.to_s.singularize}_ids" == name }
115
+ end
116
+
117
+ # Names Rails treats as secrets (filter_parameters), on top of the host's own list.
118
+ SECRET_NAMES = %i[passw secret token _key crypt salt certificate otp ssn cvv cvc].freeze
119
+
120
+ # The secrets the class leaves out of its own default serialization: columns missing from a
121
+ # new record's default serializable_hash whose name is a secret's (Devise's encrypted_password,
122
+ # not its sign-in tracking, which frontends read through `only`), plus write_only_attributes.
123
+ # Memoized per class.
124
+ def hidden_attributes(klass)
125
+ return [] unless active_record?(klass)
126
+
127
+ (@hidden ||= Concurrent::Map.new).compute_if_absent(klass) do
128
+ write_only = klass.respond_to?(:write_only_attributes) ? Array(klass.write_only_attributes).map(&:to_s) : []
129
+ left_out = begin
130
+ klass.column_names - klass.new.serializable_hash.keys
131
+ rescue StandardError
132
+ []
133
+ end
134
+ (left_out.select { |column| secret_name?(column) } | write_only).freeze
135
+ end
136
+ end
137
+
138
+ def secret_name?(name)
139
+ @secret_filter ||= ActiveSupport::ParameterFilter.new(SECRET_NAMES + Rails.application.config.filter_parameters)
140
+ @secret_filter.filter(name => "x")[name] != "x"
141
+ end
142
+
143
+ # Written in the host app or in a thecore gem. The gem that owns the file decides first:
144
+ # deploy images install the bundle inside the app (/app/vendor/bundle), so "under Rails.root"
145
+ # alone would make Rails, Devise and every other gem ours.
146
+ def our_code?(file)
147
+ return false if file.blank?
148
+
149
+ owner = Gem.loaded_specs.values
150
+ .select { |spec| file.start_with?(File.join(spec.full_gem_path, "")) }
151
+ .max_by { |spec| spec.full_gem_path.length }
152
+ return thecore_gem?(owner.name) if owner
153
+ return false if gem_dirs.any? { |dir| file.start_with?(dir) }
154
+
155
+ file.start_with?(File.join(Rails.root.to_s, ""))
156
+ end
157
+
158
+ # A gem named thecore* or depending, directly or not, on one. Memoized per gem name.
159
+ def thecore_gem?(name, seen = Set.new)
160
+ cache = (@thecore_gems ||= Concurrent::Map.new)
161
+ return cache[name] if cache.key?(name)
162
+ return false unless seen.add?(name) # a dependency cycle: decided by the other branches
163
+
164
+ spec = Gem.loaded_specs[name]
165
+ found = !spec.nil? &&
166
+ (name.start_with?("thecore") || spec.runtime_dependencies.any? { |dep| thecore_gem?(dep.name, seen) })
167
+ cache.put_if_absent(name, found)
168
+ found
169
+ end
170
+
171
+ # Where gems live, even those no spec claims (default gems, a vendored bundle).
172
+ def gem_dirs
173
+ @gem_dirs ||= (Gem.path + [Bundler.bundle_path.to_s]).map { |dir| File.join(dir, "") }.uniq.freeze
174
+ end
175
+
176
+ # A name the client asked for that is not served: logged once per request.
177
+ def drop(klass, name, reason)
178
+ seen = (ModelDrivenApi::Current.dropped_json_attrs ||= Set.new)
179
+ return unless seen.add?([klass.name, name, reason])
180
+
181
+ Rails.logger.warn("[model_driven_api] a/json_attrs: #{klass.name}##{name} dropped (#{reason})")
182
+ end
183
+
184
+ # Prepended to ActiveModel::Serialization (records and the ActiveModel objects a custom action
185
+ # may return): applies the conventions to marked options only.
186
+ module Serialization
187
+ def serializable_hash(options = nil)
188
+ return super unless RequestJsonAttrs.marked?(options)
189
+
190
+ rewritten, guarded = RequestJsonAttrs.for_class(self.class, options)
191
+ hash = super(rewritten)
192
+ guarded.each do |name|
193
+ # A refused write may already have changed the record in memory (update_column does):
194
+ # restore it so neither the next field nor the caller sees a value that was never saved.
195
+ snapshot = @attributes.deep_dup if is_a?(ActiveRecord::Base)
196
+ hash[name] = ActiveRecord::Base.while_preventing_writes { send(name) }
197
+ rescue StandardError => e
198
+ @attributes = snapshot if is_a?(ActiveRecord::Base)
199
+ RequestJsonAttrs.drop(self.class, name, "raised #{e.class}")
200
+ end
201
+ hash
202
+ end
203
+ end
204
+
205
+ # The associations of +klass+ worth preloading for marked options: real ones only, nested
206
+ # through non-polymorphic reflections.
207
+ def preloads(klass, include_option)
208
+ normalize_includes(include_option).each_with_object({}) do |(name, nested), out|
209
+ reflection = klass.reflect_on_association(name) or next
210
+ out[name] = (reflection.polymorphic? || !nested.key?(:include)) ? {} : preloads(reflection.klass, nested[:include])
211
+ end
212
+ end
213
+ end
214
+ end
215
+ end
@@ -0,0 +1,7 @@
1
+ module ModelDrivenApi
2
+ # Per-request state, reset by Rails after every request.
3
+ class Current < ActiveSupport::CurrentAttributes
4
+ # [class name, method name, reason] already logged as dropped from a/json_attrs.
5
+ attribute :dropped_json_attrs
6
+ end
7
+ end
@@ -1,3 +1,3 @@
1
1
  module ModelDrivenApi
2
- VERSION = "3.17.0".freeze
2
+ VERSION = "3.18.0".freeze
3
3
  end
@@ -22,10 +22,12 @@ require 'concerns/api_exception_management'
22
22
  require 'deep_merge/rails_compat'
23
23
 
24
24
  require "model_driven_api/engine"
25
+ require "model_driven_api/current"
25
26
 
26
27
  require "safe_sql_executor"
27
28
  require "raw_sql_grants"
28
29
  require "api/resource_attribute_set"
30
+ require "api/v2/request_json_attrs"
29
31
  require "api/model_resolver"
30
32
  require "api/custom_action_dispatcher"
31
33
  require "api/open_api/base"
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: model_driven_api
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.17.0
4
+ version: 3.18.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Gabriele Tassoni
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-25 00:00:00.000000000 Z
11
+ date: 2026-11-26 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: thecore_backend_commons
@@ -238,6 +238,7 @@ files:
238
238
  - config/initializers/cors_api_thecore.rb
239
239
  - config/initializers/default_json_attrs_registration.rb
240
240
  - config/initializers/knock.rb
241
+ - config/initializers/request_json_attrs.rb
241
242
  - config/initializers/time_with_zone.rb
242
243
  - config/initializers/wrap_parameters.rb
243
244
  - config/routes.rb
@@ -250,6 +251,7 @@ files:
250
251
  - lib/api/open_api/v2.rb
251
252
  - lib/api/open_api/v3.rb
252
253
  - lib/api/resource_attribute_set.rb
254
+ - lib/api/v2/request_json_attrs.rb
253
255
  - lib/api/v3/serializer_factory.rb
254
256
  - lib/concerns/api_exception_management.rb
255
257
  - lib/concerns/model_driven_api_application_record.rb
@@ -261,6 +263,7 @@ files:
261
263
  - lib/endpoint_validation_error.rb
262
264
  - lib/json_web_token.rb
263
265
  - lib/model_driven_api.rb
266
+ - lib/model_driven_api/current.rb
264
267
  - lib/model_driven_api/engine.rb
265
268
  - lib/model_driven_api/version.rb
266
269
  - lib/non_crud_endpoints.rb