model_driven_api 3.15.0 → 3.16.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: 9553ee66372d69d5fbe182a01d009ef9e5dc950a78bbda880b4a7ed7cd0da3b5
4
- data.tar.gz: ee749ca1d1cc97ec5d7b602f96e0f76d71f4e1cfc23dcacec2cb3a869c672c09
3
+ metadata.gz: b690a0afab20bfa86c9cfe8dbc57e9e4927a2f0f8b358975bbd5acd7eac16357
4
+ data.tar.gz: 6aadf884c1177f78eb61d9fbfeda255b7e1833197b9c9f40c6cb5a8872174cf4
5
5
  SHA512:
6
- metadata.gz: d6815fb7e5fa7729645686b3ff89e2142864835b3b0236c86ae814bb85459eb6098f3b433b09a24a91e4321aae703c0cb11df8ea351ab9b2366b08aa0b12ec8b
7
- data.tar.gz: 64abdba4f33449541eba0add552ad85be0a4d55259461215853ef826837aa46e8d5905cba9dde58bf9e48cf25b4178bbca9e6e4a2fd6fb55579f13aa376835dd
6
+ metadata.gz: 3858ad35e5cfadd584d71813f18280600b7a0507d264d15cd5c7343b005adb4adcf6b762c2d7a13bbbfd21b9a6face5210e237de04760b97b232994007fd3651
7
+ data.tar.gz: 652ea73728caa6b872df593c814a87e8920c5b1261d48dbbb9d3605c5a8a249f420e4f2b33d1cdd37b315abf70be4d14c3a83060ea111365448bb32c32a177db
data/README.md CHANGED
@@ -468,6 +468,8 @@ Executes exactly one plain `SELECT` (CTEs included), sent by any authenticated u
468
468
 
469
469
  Error body: `{ "error": "raw_sql_rejected" | "raw_sql_failed", "reason": "…", "sqlstate": "…" }` (`sqlstate` only for `query_error`). Reasons: `only_single_select`, `data_modifying_statement`, `locking_clause`, `function_not_allowed`, `syntax_error`, `query_too_large`, `not_permitted`, `timeout`, `query_error`, `result_too_large`, `nested_transaction`. v2 answers every error with 400; v3 with 422, or 413 for `result_too_large`. A missing `query` is 400 `{ "error": "Query is required" }` in both.
470
470
 
471
+ **What the query can read** is decided by the database role `thecore_raw`, under which it runs (3.16.0): no access to `ldap_servers`, `thecore_settings`, `used_tokens`, `push_subscribers`, `action_mailbox_inbound_emails`, `integration_logs`, nor to any column whose name looks like a secret (`passw`, `secret`, `token`, `_key`, `crypt`, `salt`, `certificate`, `otp`, …), so `SELECT *` or `json_agg(u)` on `users` is refused (`not_permitted`): list the columns. Every other table stays readable. Views are readable only when created `WITH (security_invoker = true)`; materialized views are not. `rails thecore:db:raw_grants` (idempotent) rebuilds the role and its grants; it runs by itself at the end of `rails thecore:db:seed`, so at every deploy, and needs the app's database user to be superuser. Otherwise it only warns, and `raw/sql` runs without the role: the log says so at every server boot, and `GET /api/v2|v3/info/raw_sql` (authenticated) answers `{ "protection": "reduced", "reasons": [...], "enforce": … }` instead of `"full"`.
472
+
471
473
  ### v2 — requires `result` key
472
474
 
473
475
  ```http
@@ -513,6 +515,7 @@ All info endpoints are available under both `/api/v2/info/` and `/api/v3/info/`.
513
515
  | `GET /info/dsl` | Yes | `json_attrs` DSL for each model |
514
516
  | `GET /info/translations` | Yes | Full i18n tree (`?locale=en`) |
515
517
  | `GET /info/settings` | Yes | All `ThecoreSettings::Setting` values |
518
+ | `GET /info/raw_sql` | Yes | Whether `raw/sql` runs under the `thecore_raw` role: `{ protection: full\|reduced, reasons, enforce }` |
516
519
  | `GET /info/swagger` | No | OpenAPI 3.0 spec (alias: `/info/openapi`) |
517
520
 
518
521
  The v2 and v3 swagger specs are different — v2 documents plain JSON CRUD + Ransack + search + bulk ops; v3 documents JSON:API envelopes + filter/sort/page params + 204 on delete.
@@ -27,6 +27,13 @@ class Api::V2::InfoController < Api::V2::ApplicationController
27
27
  render json: { server_time_utc: Time.current.utc }.to_json, status: 200
28
28
  end
29
29
 
30
+ # GET '/api/v2|v3/info/raw_sql' (host ADR 0048 §9, Odoo #6093): whether raw/sql runs under the
31
+ # thecore_raw role ("full") or without it, so secrets stay readable ("reduced", with the reasons),
32
+ # and whether RAW_SQL_ENFORCE is on. Authenticated: it tells how exposed the installation is.
33
+ def raw_sql
34
+ render json: RawSqlGrants.status, status: 200
35
+ end
36
+
30
37
  # GET '/api/v2/info/translations'
31
38
  def translations
32
39
  render json: I18n.t(".", locale: (params[:locale].presence || :it)).to_json, status: 200
data/config/routes.rb CHANGED
@@ -23,6 +23,7 @@ Rails.application.routes.draw do
23
23
  get :settings
24
24
  get :swagger
25
25
  get :openapi
26
+ get :raw_sql
26
27
  end
27
28
 
28
29
  post "authenticate" => "authentication#authenticate"
@@ -71,6 +72,7 @@ Rails.application.routes.draw do
71
72
  get :settings
72
73
  get :swagger
73
74
  get :openapi
75
+ get :raw_sql
74
76
  end
75
77
 
76
78
  namespace :raw do
@@ -0,0 +1,12 @@
1
+ # The first application of the thecore_raw role and its privileges (host ADR 0048 §3, Odoo #6093),
2
+ # for an installation that only runs db:migrate. From then on rails thecore:db:raw_grants re-applies
3
+ # them after every thecore:db:seed. Not superuser: a warning, and the migration still succeeds.
4
+ class ApplyThecoreRawGrants < ActiveRecord::Migration[7.2]
5
+ def up
6
+ RawSqlGrants.apply!(connection)
7
+ end
8
+
9
+ def down
10
+ # Nothing to undo: the role and its grants only narrow what raw/sql can read.
11
+ end
12
+ end
@@ -149,6 +149,21 @@ module Api
149
149
  },
150
150
  },
151
151
  },
152
+ "/info/raw_sql": {
153
+ "get": {
154
+ "summary": "Raw SQL protection",
155
+ "description": "Whether raw/sql runs under the thecore_raw role (protection full) or without it, so secrets stay readable (reduced, with the reasons), and whether RAW_SQL_ENFORCE is on",
156
+ "tags": ["Info"],
157
+ "security": [
158
+ "bearerAuth": [],
159
+ ],
160
+ "responses": {
161
+ "200": {
162
+ "description": "{ protection: full|reduced, reasons: [role_missing|role_not_usable|set_config_executable], enforce: boolean }",
163
+ },
164
+ },
165
+ },
166
+ },
152
167
  "/info/heartbeat": {
153
168
  "get": {
154
169
  "summary": "Heartbeat",
@@ -118,6 +118,13 @@ module Api
118
118
  "responses" => { "200" => { "description" => "App version string" } },
119
119
  },
120
120
  },
121
+ "/info/raw_sql" => {
122
+ "get" => {
123
+ "summary" => "Raw SQL protection", "tags" => ["Info"],
124
+ "security" => [{ "bearerAuth" => [] }],
125
+ "responses" => { "200" => { "description" => "{ protection: full|reduced, reasons: [...], enforce: boolean }: whether raw/sql runs under the thecore_raw role" } },
126
+ },
127
+ },
121
128
  "/info/heartbeat" => {
122
129
  "get" => {
123
130
  "summary" => "Heartbeat", "tags" => ["Info"],
@@ -346,7 +353,7 @@ module Api
346
353
 
347
354
  ### Info & utility endpoints
348
355
 
349
- `GET /info/version|heartbeat|roles|schema|dsl|translations|settings|swagger` — return plain JSON (not JSON:API).
356
+ `GET /info/version|heartbeat|roles|schema|dsl|translations|settings|raw_sql|swagger` — return plain JSON (not JSON:API).
350
357
 
351
358
  ### Raw SQL escape hatch
352
359
 
@@ -20,6 +20,13 @@ module ModelDrivenApi
20
20
  ModelDrivenApi.enforce_utc!(app.config.time_zone, db_zone)
21
21
  end
22
22
 
23
+ # Says at every server boot when raw/sql runs without the thecore_raw role (host ADR 0048 §9,
24
+ # Odoo #6093). Only for `rails server`: rake tasks such as assets:precompile in an image build
25
+ # have no database to ask.
26
+ config.after_initialize do
27
+ RawSqlGrants.report_at_boot if defined?(::Rails::Server)
28
+ end
29
+
23
30
  initializer :append_migrations do |app|
24
31
  unless app.root.to_s == root.to_s
25
32
  config.paths["db/migrate"].expanded.each do |expanded_path|
@@ -1,3 +1,3 @@
1
1
  module ModelDrivenApi
2
- VERSION = "3.15.0".freeze
2
+ VERSION = "3.16.0".freeze
3
3
  end
@@ -24,6 +24,7 @@ require 'deep_merge/rails_compat'
24
24
  require "model_driven_api/engine"
25
25
 
26
26
  require "safe_sql_executor"
27
+ require "raw_sql_grants"
27
28
  require "api/resource_attribute_set"
28
29
  require "api/model_resolver"
29
30
  require "api/custom_action_dispatcher"
@@ -0,0 +1,152 @@
1
+ # The thecore_raw database role under which SafeSqlExecutor runs the SQL of POST /api/v2|v3/raw/sql
2
+ # (host ADR 0048, Odoo #6093). The parser cannot see SQL hidden in a string (query_to_xml), so the
3
+ # barrier that keeps secrets out of reach is the role's privileges:
4
+ #
5
+ # - thecore_raw is NOLOGIN NOINHERIT and can only SELECT;
6
+ # - no privilege on EXCLUDED_TABLES;
7
+ # - on any table or view with a column whose name looks like a secret (SECRET_COLUMN), a per-column
8
+ # grant that leaves those columns out, so SELECT * or a whole-row json_agg of users is refused;
9
+ # - every other table is readable, and ALTER DEFAULT PRIVILEGES keeps new tables readable;
10
+ # - a view or materialized view reads with its owner's privileges (the superuser app), so an alias
11
+ # would slip a secret past the column-name check: only a security_invoker view is readable;
12
+ # - EXECUTE on SafeSqlExecutor::DENIED_FUNCTIONS revoked from PUBLIC (set_config above all: from a
13
+ # superuser session it would undo SET LOCAL ROLE).
14
+ #
15
+ # apply! is idempotent and rebuilds all of it from scratch, so it runs at every deploy (rake
16
+ # thecore:db:raw_grants, after thecore:db:seed): new non-secret columns become readable, new secret
17
+ # ones disappear, and a manual change to these privileges does not survive.
18
+ #
19
+ # Without superuser rights it cannot revoke set_config, so it changes nothing, logs a warning and
20
+ # returns :skipped: the deploy goes on and the executor runs without the role (protected? is false,
21
+ # reported at boot and by GET /api/v2|v3/info/raw_sql).
22
+ module RawSqlGrants
23
+ ROLE = "thecore_raw"
24
+
25
+ EXCLUDED_TABLES = %w[
26
+ ldap_servers thecore_settings used_tokens push_subscribers action_mailbox_inbound_emails integration_logs
27
+ ].freeze
28
+
29
+ # Rails' filter_parameters patterns without email, which frontends read and which is not a secret.
30
+ SECRET_COLUMN = /passw|secret|token|_key|crypt|salt|certificate|otp|ssn|cvv|cvc/i
31
+
32
+ # Tables, partitioned tables, foreign tables, plus views that read as the caller
33
+ # (security_invoker, PostgreSQL 15+). Other views and materialized views are left out.
34
+ READABLE_RELATIONS = <<~SQL
35
+ (c.relkind IN ('r', 'p', 'f') OR (c.relkind = 'v' AND EXISTS (
36
+ SELECT 1 FROM unnest(c.reloptions) o
37
+ WHERE lower(o) IN ('security_invoker=true', 'security_invoker=on', 'security_invoker=1', 'security_invoker=yes'))))
38
+ SQL
39
+
40
+ module_function
41
+
42
+ # :applied, or :skipped when the connection is not superuser.
43
+ def apply!(conn = ActiveRecord::Base.connection)
44
+ unless superuser?(conn)
45
+ Rails.logger.warn("[raw_sql] #{ROLE} grants not applied: the database user is not superuser. " \
46
+ "raw/sql runs without the role and cannot hide secrets (host ADR 0048 §9).")
47
+ return :skipped
48
+ end
49
+
50
+ conn.transaction do
51
+ ensure_role(conn)
52
+ grant_tables(conn)
53
+ revoke_functions(conn)
54
+ end
55
+ :applied
56
+ end
57
+
58
+ # True when SafeSqlExecutor can SET LOCAL ROLE thecore_raw and the role cannot undo it.
59
+ def protected?(conn = ActiveRecord::Base.connection)
60
+ reasons(conn).empty?
61
+ end
62
+
63
+ # What GET /api/v2|v3/info/raw_sql answers.
64
+ def status(conn = ActiveRecord::Base.connection)
65
+ found = reasons(conn)
66
+ {protection: found.empty? ? "full" : "reduced", reasons: found, enforce: SafeSqlExecutor.enforce?}
67
+ end
68
+
69
+ # Why the protection is reduced: [] when it is complete.
70
+ def reasons(conn = ActiveRecord::Base.connection)
71
+ return ["role_missing"] unless conn.select_value("SELECT 1 FROM pg_roles WHERE rolname = #{conn.quote(ROLE)}")
72
+
73
+ found = []
74
+ found << "role_not_usable" unless conn.select_value("SELECT pg_has_role(current_user, #{conn.quote(ROLE)}, 'MEMBER')")
75
+ if conn.select_value("SELECT has_function_privilege(#{conn.quote(ROLE)}, 'pg_catalog.set_config(text, text, boolean)', 'EXECUTE')")
76
+ found << "set_config_executable"
77
+ end
78
+ found
79
+ end
80
+
81
+ # Called by the engine when a server boots (ADR 0048 §9). Never raises: a database that cannot be
82
+ # asked must not stop the boot.
83
+ def report_at_boot
84
+ found = ActiveRecord::Base.connection_pool.with_connection { |conn| reasons(conn) }
85
+ return if found.empty?
86
+
87
+ Rails.logger.warn("[raw_sql] reduced protection (#{found.join(", ")}): raw/sql runs without the " \
88
+ "#{ROLE} role and cannot hide secrets. Run rails thecore:db:raw_grants as a superuser (host ADR 0048).")
89
+ rescue => e
90
+ Rails.logger.warn("[raw_sql] #{ROLE} protection could not be checked at boot: #{e.class}")
91
+ end
92
+
93
+ def superuser?(conn)
94
+ conn.select_value("SELECT current_setting('is_superuser')") == "on"
95
+ end
96
+
97
+ def ensure_role(conn)
98
+ conn.execute(<<~SQL)
99
+ DO $$ BEGIN
100
+ CREATE ROLE #{ROLE} NOLOGIN NOINHERIT;
101
+ EXCEPTION WHEN duplicate_object THEN NULL;
102
+ END $$
103
+ SQL
104
+ conn.execute("ALTER ROLE #{ROLE} NOLOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS")
105
+ end
106
+
107
+ def grant_tables(conn)
108
+ schema = conn.quote_table_name(conn.select_value("SELECT current_schema()"))
109
+ conn.execute("GRANT USAGE ON SCHEMA #{schema} TO #{ROLE}")
110
+ # REVOKE ALL on a table also drops its column grants, so stale ones go too.
111
+ conn.execute("REVOKE ALL ON ALL TABLES IN SCHEMA #{schema} FROM #{ROLE}")
112
+ conn.execute("REVOKE ALL ON ALL SEQUENCES IN SCHEMA #{schema} FROM #{ROLE}")
113
+ conn.execute("ALTER DEFAULT PRIVILEGES IN SCHEMA #{schema} GRANT SELECT ON TABLES TO #{ROLE}")
114
+
115
+ columns_by_relation(conn).each do |relation, columns|
116
+ next if EXCLUDED_TABLES.include?(relation)
117
+
118
+ table = "#{schema}.#{conn.quote_table_name(relation)}"
119
+ readable = columns.grep_v(SECRET_COLUMN)
120
+ if readable.size == columns.size
121
+ conn.execute("GRANT SELECT ON #{table} TO #{ROLE}")
122
+ elsif readable.any?
123
+ conn.execute("GRANT SELECT (#{readable.map { |c| conn.quote_column_name(c) }.join(", ")}) ON #{table} TO #{ROLE}")
124
+ end
125
+ end
126
+ end
127
+
128
+ # { relation name => [column names] } of the relations thecore_raw may read in the current schema. pg_attribute rather than
129
+ # information_schema, which lists only the columns the current user may read.
130
+ def columns_by_relation(conn)
131
+ conn.select_rows(<<~SQL).group_by(&:first).transform_values { |rows| rows.map(&:last) }
132
+ SELECT c.relname, a.attname
133
+ FROM pg_class c
134
+ JOIN pg_namespace n ON n.oid = c.relnamespace
135
+ JOIN pg_attribute a ON a.attrelid = c.oid
136
+ WHERE n.nspname = current_schema() AND #{READABLE_RELATIONS} AND a.attnum > 0 AND NOT a.attisdropped
137
+ ORDER BY c.relname, a.attnum
138
+ SQL
139
+ end
140
+
141
+ # Every overload of each denied function in pg_catalog.
142
+ def revoke_functions(conn)
143
+ names = SafeSqlExecutor::DENIED_FUNCTIONS.map { |name| conn.quote(name) }.join(", ")
144
+ conn.select_values(<<~SQL).each do |signature|
145
+ SELECT p.oid::regprocedure::text
146
+ FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
147
+ WHERE n.nspname = 'pg_catalog' AND p.proname IN (#{names})
148
+ SQL
149
+ conn.execute("REVOKE EXECUTE ON FUNCTION #{signature} FROM PUBLIC, #{ROLE}")
150
+ end
151
+ end
152
+ end
@@ -11,7 +11,9 @@ require "securerandom"
11
11
  # 2. The query runs in a transaction of its own: READ ONLY, statement/lock timeouts, work_mem and
12
12
  # temp_file_limit, through select_all (one statement over exec_params, never execute), and is
13
13
  # always rolled back. Session advisory locks survive a rollback, so pg_advisory_unlock_all()
14
- # runs afterwards. The database role that hides secrets comes with Odoo #6093.
14
+ # runs afterwards. When RawSqlGrants.protected?, the query runs as the thecore_raw role
15
+ # (Odoo #6093), which cannot read secret tables and columns nor call set_config: that, not the
16
+ # parser, is what keeps secrets out of reach.
15
17
  #
16
18
  # Errors never carry PostgreSQL's message: the caller gets Rejected/Failed with a reason, the
17
19
  # details go to the Rails log tagged with the correlation id (the request id).
@@ -168,9 +170,12 @@ module SafeSqlExecutor
168
170
  conn.execute("SET LOCAL lock_timeout = #{conn.quote(setting(:lock_timeout))}")
169
171
  conn.execute("SET LOCAL work_mem = #{conn.quote(setting(:work_mem))}")
170
172
  # Superuser-only (PGC_SUSET): on an installation where the app isn't superuser it is skipped.
171
- if conn.select_value("SELECT current_setting('is_superuser')") == "on"
173
+ if RawSqlGrants.superuser?(conn)
172
174
  conn.execute("SET LOCAL temp_file_limit = #{conn.quote(setting(:temp_file_limit))}")
173
175
  end
176
+ # The barrier that hides secrets (Odoo #6093). Without it (grants never applied, app not
177
+ # superuser) the query still runs READ ONLY with the parser in front, as RawSqlGrants reports.
178
+ conn.execute("SET LOCAL ROLE #{RawSqlGrants::ROLE}") if RawSqlGrants.protected?(conn)
174
179
  rows = conn.select_all(query, "RawSql").to_a
175
180
  raise ActiveRecord::Rollback
176
181
  end
@@ -1,4 +1,22 @@
1
- # desc "Explaining what the task does"
2
- # task :model_driven_api do
3
- # # Task goes here
4
- # end
1
+ namespace :thecore do
2
+ namespace :db do
3
+ desc "Rebuilds the thecore_raw role and its privileges, under which raw/sql runs (idempotent; ADR 0048)."
4
+ task raw_grants: :environment do
5
+ result = RawSqlGrants.apply!
6
+ puts(result == :applied ? "thecore_raw grants applied" : "thecore_raw grants skipped: the database user is not superuser")
7
+ end
8
+
9
+ # The hook below. As a prerequisite it runs once every rake file is loaded, so the grants are
10
+ # appended after thecore_auth_commons' seed actions whatever order the engines load in.
11
+ task :raw_grants_after_seed do
12
+ Rake::Task["thecore:db:seed"].enhance do
13
+ Rake::Task["thecore:db:raw_grants"].reenable
14
+ Rake::Task["thecore:db:raw_grants"].invoke
15
+ end
16
+ end
17
+ end
18
+ end
19
+
20
+ # thecore:db:seed runs after the migrations both in thecore:db:init/update and in the image
21
+ # entrypoint (db:migrate then thecore:db:seed), so every deploy ends by re-applying the grants.
22
+ Rake::Task.define_task("thecore:db:seed" => "thecore:db:raw_grants_after_seed")
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: model_driven_api
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.15.0
4
+ version: 3.16.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Gabriele Tassoni
@@ -243,6 +243,7 @@ files:
243
243
  - config/routes.rb
244
244
  - db/migrate/20210519145438_create_used_tokens.rb
245
245
  - db/migrate/20210528111450_rename_valid_to_is_valid_in_used_token.rb
246
+ - db/migrate/20261125120000_apply_thecore_raw_grants.rb
246
247
  - lib/api/custom_action_dispatcher.rb
247
248
  - lib/api/model_resolver.rb
248
249
  - lib/api/open_api/base.rb
@@ -263,6 +264,7 @@ files:
263
264
  - lib/model_driven_api/engine.rb
264
265
  - lib/model_driven_api/version.rb
265
266
  - lib/non_crud_endpoints.rb
267
+ - lib/raw_sql_grants.rb
266
268
  - lib/safe_sql_executor.rb
267
269
  - lib/tasks/model_driven_api_tasks.rake
268
270
  homepage: https://github.com/gabrieletassoni/model_driven_api