model_driven_api 3.14.1 → 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 +4 -4
- data/README.md +19 -17
- data/app/controllers/api/v2/application_controller.rb +3 -0
- data/app/controllers/api/v2/auth/oauth_controller.rb +0 -36
- data/app/controllers/api/v2/info_controller.rb +7 -0
- data/app/controllers/api/v2/raw_controller.rb +14 -13
- data/app/controllers/api/v3/raw_controller.rb +10 -6
- data/config/routes.rb +2 -7
- data/db/migrate/20261125120000_apply_thecore_raw_grants.rb +12 -0
- data/lib/api/open_api/v2.rb +23 -2
- data/lib/api/open_api/v3.rb +22 -6
- data/lib/model_driven_api/engine.rb +7 -0
- data/lib/model_driven_api/version.rb +1 -1
- data/lib/model_driven_api.rb +1 -0
- data/lib/raw_sql_grants.rb +152 -0
- data/lib/safe_sql_executor.rb +229 -11
- data/lib/tasks/model_driven_api_tasks.rake +22 -4
- metadata +23 -2
- data/app/controllers/api/v3/auth/oauth_controller.rb +0 -4
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: b690a0afab20bfa86c9cfe8dbc57e9e4927a2f0f8b358975bbd5acd7eac16357
|
|
4
|
+
data.tar.gz: 6aadf884c1177f78eb61d9fbfeda255b7e1833197b9c9f40c6cb5a8872174cf4
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 3858ad35e5cfadd584d71813f18280600b7a0507d264d15cd5c7343b005adb4adcf6b762c2d7a13bbbfd21b9a6face5210e237de04760b97b232994007fd3651
|
|
7
|
+
data.tar.gz: 652ea73728caa6b872df593c814a87e8920c5b1261d48dbbb9d3605c5a8a249f420e4f2b33d1cdd37b315abf70be4d14c3a83060ea111365448bb32c32a177db
|
data/README.md
CHANGED
|
@@ -20,7 +20,7 @@ A Rails engine that auto-generates a versioned REST API by introspecting your Ac
|
|
|
20
20
|
- OAuth2 support: Google Workspace and Microsoft Entra ID
|
|
21
21
|
- LDAP / Active Directory authentication (via host app headers)
|
|
22
22
|
- Custom actions on any model — two patterns supported (v2 and v3)
|
|
23
|
-
-
|
|
23
|
+
- Raw SQL endpoint (v2 and v3): one plain SELECT, read-only, with limits
|
|
24
24
|
- Self-generated OpenAPI 3.0 / Swagger documentation (v2 and v3)
|
|
25
25
|
- JSON:API sideloading with hybrid defaults (`json_attrs[:include]` + `?include=` override)
|
|
26
26
|
- JSON:API sparse fieldsets (`?fields[type]=f1,f2`)
|
|
@@ -101,25 +101,12 @@ Accept: application/vnd.api+json
|
|
|
101
101
|
|
|
102
102
|
## OAuth2 Authorization
|
|
103
103
|
|
|
104
|
-
OAuth2 is enabled when the relevant environment variables are set (see below).
|
|
104
|
+
OAuth2 is enabled when the relevant environment variables are set (see below). The only flow is the server-side OmniAuth callback (the frontend token exchange `POST /api/v2|v3/auth/jwt` was removed in 3.15.0).
|
|
105
105
|
|
|
106
106
|
### Server-side OmniAuth callback (traditional)
|
|
107
107
|
|
|
108
108
|
Set redirect URI to `http://yourdomain/auth/:provider/callback`. The OmniAuth middleware redirects to `/api/v2/auth/:provider/callback`, which returns the user JSON and a `Token` header.
|
|
109
109
|
|
|
110
|
-
### Frontend token exchange (`POST /api/v2/auth/jwt`)
|
|
111
|
-
|
|
112
|
-
For SPA frontends that obtain the OAuth token themselves:
|
|
113
|
-
|
|
114
|
-
```http
|
|
115
|
-
POST /api/v2/auth/jwt
|
|
116
|
-
Content-Type: application/json
|
|
117
|
-
|
|
118
|
-
{ "provider": "google", "provider_token": "<google-access-token>" }
|
|
119
|
-
```
|
|
120
|
-
|
|
121
|
-
The backend verifies the token against the provider's userinfo endpoint and returns a JWT.
|
|
122
|
-
|
|
123
110
|
### Register OAuth apps
|
|
124
111
|
|
|
125
112
|
#### Google
|
|
@@ -467,7 +454,21 @@ concern at all keeps the bare default.
|
|
|
467
454
|
|
|
468
455
|
## Raw SQL endpoint
|
|
469
456
|
|
|
470
|
-
Executes
|
|
457
|
+
Executes exactly one plain `SELECT` (CTEs included), sent by any authenticated user. PostgreSQL's own parser (`pg_query`) refuses several statements, `SELECT INTO`, `FOR UPDATE/SHARE`, any `INSERT/UPDATE/DELETE/MERGE` (also inside a CTE) and side-effect functions (`set_config`, advisory locks, large-object writes, `pg_sleep*`, `pg_notify`, backend signalling). The query runs in its own `READ ONLY` transaction with limits and is always rolled back. Errors never carry PostgreSQL's message.
|
|
458
|
+
|
|
459
|
+
| ENV | Default | |
|
|
460
|
+
|---|---|---|
|
|
461
|
+
| `RAW_SQL_STATEMENT_TIMEOUT` | `15s` | `SET LOCAL statement_timeout` |
|
|
462
|
+
| `RAW_SQL_LOCK_TIMEOUT` | `1s` | `SET LOCAL lock_timeout` |
|
|
463
|
+
| `RAW_SQL_WORK_MEM` | `16MB` | `SET LOCAL work_mem` |
|
|
464
|
+
| `RAW_SQL_TEMP_FILE_LIMIT` | `256MB` | `SET LOCAL temp_file_limit` (only when the app is superuser) |
|
|
465
|
+
| `RAW_SQL_MAX_QUERY_BYTES` | `102400` | longer queries are rejected (`query_too_large`) |
|
|
466
|
+
| `RAW_SQL_MAX_RESULT_BYTES` | `10485760` | larger results fail (`result_too_large`) |
|
|
467
|
+
| `RAW_SQL_ENFORCE` | `true` | `false`: a rejection (never a timeout or failure) is logged (`IntegrationLog` warning when the host has that model) and the query runs again the old way. A rollout switch for frontends not verified yet. |
|
|
468
|
+
|
|
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
|
+
|
|
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"`.
|
|
471
472
|
|
|
472
473
|
### v2 — requires `result` key
|
|
473
474
|
|
|
@@ -477,7 +478,7 @@ Authorization: Bearer <jwt>
|
|
|
477
478
|
Content-Type: application/json
|
|
478
479
|
|
|
479
480
|
{
|
|
480
|
-
"query": "SELECT json_agg(
|
|
481
|
+
"query": "SELECT json_agg(r) AS result FROM (SELECT id, name FROM roles) r"
|
|
481
482
|
}
|
|
482
483
|
```
|
|
483
484
|
|
|
@@ -514,6 +515,7 @@ All info endpoints are available under both `/api/v2/info/` and `/api/v3/info/`.
|
|
|
514
515
|
| `GET /info/dsl` | Yes | `json_attrs` DSL for each model |
|
|
515
516
|
| `GET /info/translations` | Yes | Full i18n tree (`?locale=en`) |
|
|
516
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 }` |
|
|
517
519
|
| `GET /info/swagger` | No | OpenAPI 3.0 spec (alias: `/info/openapi`) |
|
|
518
520
|
|
|
519
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.
|
|
@@ -280,6 +280,9 @@ class Api::V2::ApplicationController < ActionController::API
|
|
|
280
280
|
|
|
281
281
|
def extract_model
|
|
282
282
|
@model = Api::ModelResolver.resolve(params, controller_path, controller_name)
|
|
283
|
+
# A catchall or custom-action path that names no class: nothing can serve it (the CRUD and
|
|
284
|
+
# the dispatcher need a class). Info endpoints resolve no model on purpose and carry neither param.
|
|
285
|
+
return not_found! if @model.nil? && (params[:path].present? || params[:ctrl].present?)
|
|
283
286
|
@body = (params[@model.model_name.singular].presence || params[@model.model_name.route_key]) rescue params
|
|
284
287
|
rescue Api::ModelResolver::NotFound
|
|
285
288
|
not_found!
|
|
@@ -33,41 +33,5 @@ module Api::V2::Auth
|
|
|
33
33
|
def failure
|
|
34
34
|
render json: { error: "OAuth authentication failed" }, status: :unauthorized
|
|
35
35
|
end
|
|
36
|
-
|
|
37
|
-
def exchange_token
|
|
38
|
-
provider_token = params[:provider_token]
|
|
39
|
-
provider = params[:provider] # 'google' or 'microsoft'
|
|
40
|
-
|
|
41
|
-
user_info = case provider
|
|
42
|
-
when 'google'
|
|
43
|
-
uri = URI("https://www.googleapis.com/oauth2/v3/userinfo")
|
|
44
|
-
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
|
|
45
|
-
req = Net::HTTP::Get.new(uri)
|
|
46
|
-
req["Authorization"] = "Bearer #{provider_token}"
|
|
47
|
-
http.request(req)
|
|
48
|
-
end
|
|
49
|
-
JSON.parse(res.body)
|
|
50
|
-
when 'microsoft'
|
|
51
|
-
uri = URI("https://graph.microsoft.com/v1.0/me")
|
|
52
|
-
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
|
|
53
|
-
req = Net::HTTP::Get.new(uri)
|
|
54
|
-
req["Authorization"] = "Bearer #{provider_token}"
|
|
55
|
-
http.request(req)
|
|
56
|
-
end
|
|
57
|
-
JSON.parse(res.body)
|
|
58
|
-
else
|
|
59
|
-
return render json: { error: "Unknown provider" }, status: :unprocessable_entity
|
|
60
|
-
end
|
|
61
|
-
|
|
62
|
-
email = user_info["mail"] || user_info["email"] || user_info["userPrincipalName"]
|
|
63
|
-
user = User.find_by(email: email)
|
|
64
|
-
|
|
65
|
-
unless user&.active_for_authentication?
|
|
66
|
-
return render json: { error: "User not registered" }, status: :unauthorized
|
|
67
|
-
end
|
|
68
|
-
|
|
69
|
-
response.set_header("Token", JsonWebToken.encode(user_id: user.id))
|
|
70
|
-
render json: user, status: :ok
|
|
71
|
-
end
|
|
72
36
|
end
|
|
73
37
|
end
|
|
@@ -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
|
|
@@ -1,22 +1,23 @@
|
|
|
1
|
-
#
|
|
1
|
+
# POST|GET /api/v2/raw/sql: one SELECT that returns a column called "result" (typically json_agg),
|
|
2
|
+
# answered as that value. Executed by SafeSqlExecutor (host ADR 0048, Odoo #5835). Every error is
|
|
3
|
+
# 400, as it always was in v2, with a body { error, reason } that never carries PostgreSQL's message.
|
|
2
4
|
class Api::V2::RawController < Api::V2::ApplicationController
|
|
3
|
-
# Info uses a different auth method: username and password
|
|
4
|
-
# skip_before_action :authenticate_request, only: [:version, :swagger, :openapi], raise: false
|
|
5
5
|
skip_before_action :extract_model
|
|
6
|
-
|
|
7
|
-
# api :GET, '/api/v2/raw/sql'
|
|
8
|
-
def sql
|
|
9
|
-
# if params is nil, render 400
|
|
10
|
-
render json: { error: "Query is required" }, status: 400 and return if params[:query].nil?
|
|
11
6
|
|
|
12
|
-
|
|
7
|
+
def sql
|
|
8
|
+
render json: {error: "Query is required"}, status: 400 and return if params[:query].nil?
|
|
13
9
|
|
|
14
|
-
first_element =
|
|
10
|
+
first_element = begin
|
|
11
|
+
SafeSqlExecutor.execute_select(params[:query].to_s, correlation_id: request.request_id).first
|
|
12
|
+
rescue SafeSqlExecutor::Error => e
|
|
13
|
+
render json: e, status: 400 and return
|
|
14
|
+
rescue ArgumentError, ActiveRecord::StatementInvalid
|
|
15
|
+
# Only the RAW_SQL_ENFORCE=false fallback raises these: v2 always answered them like this.
|
|
16
|
+
nil
|
|
17
|
+
end
|
|
15
18
|
|
|
16
|
-
|
|
17
|
-
render json: { error: "Query must return a key called result" }, status: 400 and return if first_element.nil? || !first_element.key?("result")
|
|
19
|
+
render json: {error: "Query must return a key called result"}, status: 400 and return if first_element.nil? || !first_element.key?("result")
|
|
18
20
|
|
|
19
21
|
render json: first_element["result"], status: 200
|
|
20
22
|
end
|
|
21
|
-
|
|
22
23
|
end
|
|
@@ -1,14 +1,18 @@
|
|
|
1
|
+
# POST|GET /api/v3/raw/sql: the rows of one SELECT as a plain JSON array (ADR 0004). Executed by
|
|
2
|
+
# SafeSqlExecutor (host ADR 0048, Odoo #5835): 422 for a rejected or failed query, 413 for a result
|
|
3
|
+
# over RAW_SQL_MAX_RESULT_BYTES, never with PostgreSQL's message.
|
|
1
4
|
class Api::V3::RawController < Api::V3::ApplicationController
|
|
2
5
|
skip_before_action :extract_model
|
|
3
6
|
|
|
4
7
|
def sql
|
|
5
|
-
return render json: {
|
|
8
|
+
return render json: {error: "Query is required"}, status: 400 if params[:query].nil?
|
|
6
9
|
|
|
7
|
-
result = SafeSqlExecutor.execute_select(params[:query])
|
|
10
|
+
result = SafeSqlExecutor.execute_select(params[:query].to_s, correlation_id: request.request_id)
|
|
8
11
|
render json: result, status: 200
|
|
9
|
-
rescue
|
|
10
|
-
render json:
|
|
11
|
-
rescue ActiveRecord::StatementInvalid => e
|
|
12
|
-
|
|
12
|
+
rescue SafeSqlExecutor::Error => e
|
|
13
|
+
render json: e, status: e.http_status
|
|
14
|
+
rescue ArgumentError, ActiveRecord::StatementInvalid => e
|
|
15
|
+
# Only the RAW_SQL_ENFORCE=false fallback raises these, answered as before ADR 0048.
|
|
16
|
+
render json: {error: e.message}, status: 400
|
|
13
17
|
end
|
|
14
18
|
end
|
data/config/routes.rb
CHANGED
|
@@ -10,12 +10,6 @@ Rails.application.routes.draw do
|
|
|
10
10
|
end
|
|
11
11
|
namespace :api, constraints: { format: :json } do
|
|
12
12
|
namespace :v3 do
|
|
13
|
-
if ThecoreAuthCommons.oauth_vars?
|
|
14
|
-
namespace :auth do
|
|
15
|
-
post :jwt, to: "oauth#exchange_token"
|
|
16
|
-
end
|
|
17
|
-
end
|
|
18
|
-
|
|
19
13
|
resources :users
|
|
20
14
|
|
|
21
15
|
namespace :info do
|
|
@@ -29,6 +23,7 @@ Rails.application.routes.draw do
|
|
|
29
23
|
get :settings
|
|
30
24
|
get :swagger
|
|
31
25
|
get :openapi
|
|
26
|
+
get :raw_sql
|
|
32
27
|
end
|
|
33
28
|
|
|
34
29
|
post "authenticate" => "authentication#authenticate"
|
|
@@ -61,7 +56,6 @@ Rails.application.routes.draw do
|
|
|
61
56
|
match ":provider/callback", to: "oauth#callback", via: [:get, :post]
|
|
62
57
|
get :failure, to: "oauth#failure"
|
|
63
58
|
get ":provider", to: redirect("/auth/%{provider}") # triggers OmniAuth middleware
|
|
64
|
-
post :jwt, to: "oauth#exchange_token" # Optional endpoint to allow frontends to send the OAuth token
|
|
65
59
|
end
|
|
66
60
|
end
|
|
67
61
|
|
|
@@ -78,6 +72,7 @@ Rails.application.routes.draw do
|
|
|
78
72
|
get :settings
|
|
79
73
|
get :swagger
|
|
80
74
|
get :openapi
|
|
75
|
+
get :raw_sql
|
|
81
76
|
end
|
|
82
77
|
|
|
83
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
|
data/lib/api/open_api/v2.rb
CHANGED
|
@@ -66,7 +66,7 @@ module Api
|
|
|
66
66
|
"/raw/sql": {
|
|
67
67
|
"post": {
|
|
68
68
|
"summary": "Raw SQL query execution of SELECT queries",
|
|
69
|
-
"description": "Executes a SQL query on the underlying PostgreSQL database, the query must return the JSON in a **result** key (please note in the examples the _SELECT json_agg(u) AS result_ or in the more complex one the _SELECT jsonb_agg(pick_data) AS result_, they always use the **result** return object).\n \nDesigned for SELECT queries that use the json_agg function to aggregate results into JSON arrays, which must return the JSON in a **result** key.\n \nOther query types are not recommended and may be restricted for security and performance reasons.\n \
|
|
69
|
+
"description": "Executes a SQL query on the underlying PostgreSQL database, the query must return the JSON in a **result** key (please note in the examples the _SELECT json_agg(u) AS result_ or in the more complex one the _SELECT jsonb_agg(pick_data) AS result_, they always use the **result** return object).\n \nDesigned for SELECT queries that use the json_agg function to aggregate results into JSON arrays, which must return the JSON in a **result** key.\n \nOther query types are not recommended and may be restricted for security and performance reasons.\n \nExactly one plain SELECT is allowed, checked with PostgreSQL's own parser: no several statements, no SELECT INTO, no FOR UPDATE/SHARE, no INSERT/UPDATE/DELETE/MERGE (not even inside a CTE), no set_config, advisory locks, large-object writes, pg_sleep, pg_notify or backend signalling. It runs in a READ ONLY transaction, always rolled back, with a statement timeout (RAW_SQL_STATEMENT_TIMEOUT, 15s), a lock timeout, work_mem and temp_file_limit; the query may be at most RAW_SQL_MAX_QUERY_BYTES (100 KB) and the result at most RAW_SQL_MAX_RESULT_BYTES (10 MB).\n \nEvery error answers 400 with `{ \"error\": \"raw_sql_rejected\" | \"raw_sql_failed\", \"reason\": … }` (reasons: only_single_select, data_modifying_statement, locking_clause, function_not_allowed, syntax_error, query_too_large, not_permitted, timeout, query_error with its `sqlstate`, result_too_large, nested_transaction), never with PostgreSQL's message.\n \nQueries can be as simple as:\n \n```sql\nSELECT json_agg(u) AS result\nFROM users u\nWHERE u.active = true;\n```\n \nor more complex, using joins, subqueries, CTEs, and other SQL features. like:\n \n```sql\nWITH pick_data AS (\n SELECT p.id,\n p.project_id,\n p.quantity,\n p.created_at,\n p.updated_at,\n p.notes,\n p.document_id,\n p.external_code,\n p.reference_project_id,\n p.reference_row,\n p.closed,\n p.parent_reference_row,\n p.packages,\n p.weight,\n p.dispatched_quantity,\n p.override_item_reference,\n p.override_item_description,\n p.override_item_measure_unit,\n p.lock_version,\n p.user_id,\n COALESCE(SUM(pr.quantity), 0) AS quantity_detected,\n COALESCE(p.quantity, 0) - COALESCE(SUM(pr.quantity), 0) AS quantity_remaining,\n json_agg(\n jsonb_build_object(\n 'id',\n pr.id,\n 'item_id',\n pr.item_id,\n 'location_id',\n pr.location_id,\n 'quantity',\n pr.quantity\n )\n ) AS project_rows,\n jsonb_build_object(\n 'id',\n l.id,\n 'name',\n l.name,\n 'description',\n l.description\n ) AS location,\n jsonb_build_object(\n 'id',\n i.id,\n 'code',\n i.code,\n 'created_at',\n i.created_at,\n 'updated_at',\n i.updated_at,\n 'description',\n i.description,\n 'has_serials',\n i.has_serials,\n 'external_code',\n i.external_code,\n 'barcode',\n i.barcode,\n 'weight',\n i.weight,\n 'quantity',\n i.quantity,\n 'package_quantity',\n i.package_quantity,\n 'locked_quantity',\n i.locked_quantity,\n 'disabled',\n i.disabled,\n 'measure_unit',\n jsonb_build_object('id', mu.id, 'name', mu.name),\n 'location',\n jsonb_build_object('id', il.id, 'name', il.name),\n 'locations',\n (\n SELECT jsonb_agg(\n jsonb_build_object('id', loc.id, 'name', loc.name)\n )\n FROM locations loc\n JOIN item_locations il ON il.location_id = loc.id\n WHERE il.item_id = i.id\n ),\n 'additional_barcodes',\n (\n SELECT jsonb_agg(\n jsonb_build_object('id', ab.id, 'code', ab.code)\n )\n FROM additional_barcodes ab\n WHERE ab.item_id = i.id\n )\n ) AS item\n FROM picks p\n LEFT JOIN project_rows pr ON pr.pick_id = p.id\n LEFT JOIN locations l ON l.id = p.location_id\n LEFT JOIN items i ON i.id = p.item_id\n LEFT JOIN measure_units mu ON mu.id = i.measure_unit_id\n LEFT JOIN locations il ON il.id = i.location_id\n WHERE p.project_id = 16130\n GROUP BY p.id,\n l.id,\n i.id,\n mu.id,\n il.id\n)\nSELECT jsonb_agg(pick_data) AS result\nFROM pick_data;\n```\n \nLet's break down the provided SQL query and understand why it uses a Common Table Expression (CTE) and how it can improve performance.\n \n### Explanation of the complex Query\n \nThe provided query uses a CTE named `pick_data` to gather and aggregate data from multiple tables (`picks`, `project_rows`, `locations`, `items`, `measure_units`, `item_locations`, and `additional_barcodes`). The final result is a JSON array of aggregated data.\n \n#### Key Components of the Query:\n \n1. **CTE Definition**:\n \n ```sql\n WITH pick_data AS (\n -- Subquery content\n )\n ```\n \n The CTE `pick_data` is defined to encapsulate the logic of the subquery. This makes the query more readable and modular.\n \n2. **Data Selection and Aggregation**:\n Inside the CTE, data is selected and aggregated from various tables. Key operations include:\n \n - **Column Selection**: Selecting specific columns from the `picks` table.\n - **Aggregation**: Using `COALESCE` and `SUM` to calculate `quantity_detected` and `quantity_remaining`.\n - **JSON Aggregation**: Using `json_agg` and `jsonb_build_object` to create JSON objects and arrays for nested data structures.\n \n3. **Final Selection**:\n ```sql\n SELECT jsonb_agg(pick_data) AS result FROM pick_data;\n ```\n The final selection aggregates all rows from the CTE `pick_data` into a single JSON array.\n \n### Why Use a CTE?\n \n1. **Readability and Maintainability**:\n \n - **Modular Code**: By using a CTE, the complex logic is encapsulated in a named subquery, making the main query easier to read and understand.\n - **Reusability**: The CTE can be reused within the same query if needed, avoiding duplication of code.\n \n2. **Performance**:\n - **Optimization**: Modern SQL engines can optimize CTEs effectively. They can be materialized (computed once and stored) or inlined (expanded in the main query) based on the query plan.\n - **Intermediate Results**: CTEs allow breaking down complex queries into simpler steps, which can sometimes help the SQL engine optimize each step more effectively.\n \n### Documentation for Editing Generic Queries\n \nWhen editing or creating new queries, consider the following steps and best practices:\n \n1. **Identify the Purpose**:\n \n - Clearly define what the query needs to achieve. Understand the data relationships and the final output format.\n \n2. **Use CTEs for Complex Logic**:\n \n - Break down complex queries into smaller, manageable parts using CTEs. This improves readability and maintainability.\n \n3. **Optimize Aggregations and Joins**:\n \n - Ensure that aggregations and joins are optimized. Use indexes where appropriate and avoid unnecessary computations.\n \n4. **Leverage JSON Functions**:\n \n - Use JSON functions (`json_agg`, `jsonb_build_object`, etc.) to handle nested data structures effectively.\n \n5. **Test and Validate**:\n - Test the query with different datasets to ensure it performs well and returns the correct results. Validate the output format.\n \n### Example of a Generic Query Using CTE\n \nHere's a generic example to illustrate how to use a CTE in a query:\n \n```sql\n \n\nWITH data_aggregation AS (\n SELECT\n t1.id,\n t1.name,\n SUM(t2.value) AS total_value,\n json_agg(\n jsonb_build_object(\n 'id', t2.id,\n 'value', t2.value\n )\n ) AS details\n FROM table1 t1\n LEFT JOIN table2 t2 ON t2.table1_id = t1.id\n GROUP BY t1.id\n)\nSELECT jsonb_agg(data_aggregation) AS result FROM data_aggregation;\n```\n \n### Conclusion\n \nUsing CTEs in SQL queries helps in organizing complex logic, improving readability, and potentially enhancing performance. When editing or creating new queries, follow best practices such as breaking down complex logic, optimizing joins and aggregations, and leveraging JSON functions for nested data structures.\n",
|
|
70
70
|
"tags": ["Raw"],
|
|
71
71
|
"security": [
|
|
72
72
|
"bearerAuth": [],
|
|
@@ -91,7 +91,7 @@ module Api
|
|
|
91
91
|
},
|
|
92
92
|
},
|
|
93
93
|
"400": {
|
|
94
|
-
"description": "
|
|
94
|
+
"description": "Query missing, rejected or failed (error raw_sql_rejected/raw_sql_failed with a reason), or not returning a key called result",
|
|
95
95
|
"content": {
|
|
96
96
|
"application/json": {
|
|
97
97
|
"schema": {
|
|
@@ -100,6 +100,12 @@ module Api
|
|
|
100
100
|
"error": {
|
|
101
101
|
"type": "string",
|
|
102
102
|
},
|
|
103
|
+
"reason": {
|
|
104
|
+
"type": "string",
|
|
105
|
+
},
|
|
106
|
+
"sqlstate": {
|
|
107
|
+
"type": "string",
|
|
108
|
+
},
|
|
103
109
|
},
|
|
104
110
|
},
|
|
105
111
|
},
|
|
@@ -143,6 +149,21 @@ module Api
|
|
|
143
149
|
},
|
|
144
150
|
},
|
|
145
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
|
+
},
|
|
146
167
|
"/info/heartbeat": {
|
|
147
168
|
"get": {
|
|
148
169
|
"summary": "Heartbeat",
|
data/lib/api/open_api/v3.rb
CHANGED
|
@@ -62,6 +62,15 @@ module Api
|
|
|
62
62
|
"type" => "array",
|
|
63
63
|
"items" => { "type" => "object", "additionalProperties" => true },
|
|
64
64
|
}
|
|
65
|
+
error_schema = {
|
|
66
|
+
"type" => "object",
|
|
67
|
+
"properties" => { "error" => { "type" => "string" }, "reason" => { "type" => "string" }, "sqlstate" => { "type" => "string" } },
|
|
68
|
+
}
|
|
69
|
+
error_responses = {
|
|
70
|
+
"400" => { "description" => "Query is required" },
|
|
71
|
+
"413" => { "description" => "Result over RAW_SQL_MAX_RESULT_BYTES", "content" => { "application/json" => { "schema" => error_schema } } },
|
|
72
|
+
"422" => { "description" => "Rejected (raw_sql_rejected) or failed (raw_sql_failed); reason, and sqlstate for a query_error. Never PostgreSQL's message", "content" => { "application/json" => { "schema" => error_schema } } },
|
|
73
|
+
}
|
|
65
74
|
query_param = {
|
|
66
75
|
"name" => "query",
|
|
67
76
|
"in" => "query",
|
|
@@ -78,23 +87,23 @@ module Api
|
|
|
78
87
|
"get" => {
|
|
79
88
|
"summary" => "Raw SQL (GET)",
|
|
80
89
|
"tags" => ["Raw"],
|
|
81
|
-
"description" => "Execute
|
|
90
|
+
"description" => "Execute exactly one plain SELECT (pg_query-checked) in a READ ONLY transaction with timeouts, always rolled back. Returns rows as a plain JSON array (not JSON:API).",
|
|
82
91
|
"security" => [{ "bearerAuth" => [] }],
|
|
83
92
|
"parameters" => [query_param],
|
|
84
93
|
"responses" => {
|
|
85
94
|
"200" => { "description" => "Rows", "content" => { "application/json" => { "schema" => response_schema } } },
|
|
86
|
-
|
|
95
|
+
**error_responses,
|
|
87
96
|
},
|
|
88
97
|
},
|
|
89
98
|
"post" => {
|
|
90
99
|
"summary" => "Raw SQL (POST)",
|
|
91
100
|
"tags" => ["Raw"],
|
|
92
|
-
"description" => "Execute
|
|
101
|
+
"description" => "Execute exactly one plain SELECT (pg_query-checked) in a READ ONLY transaction with timeouts, always rolled back. Returns rows as a plain JSON array (not JSON:API).",
|
|
93
102
|
"security" => [{ "bearerAuth" => [] }],
|
|
94
103
|
"requestBody" => { "required" => true, "content" => { "application/json" => { "schema" => body_schema } } },
|
|
95
104
|
"responses" => {
|
|
96
105
|
"200" => { "description" => "Rows", "content" => { "application/json" => { "schema" => response_schema } } },
|
|
97
|
-
|
|
106
|
+
**error_responses,
|
|
98
107
|
},
|
|
99
108
|
},
|
|
100
109
|
},
|
|
@@ -109,6 +118,13 @@ module Api
|
|
|
109
118
|
"responses" => { "200" => { "description" => "App version string" } },
|
|
110
119
|
},
|
|
111
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
|
+
},
|
|
112
128
|
"/info/heartbeat" => {
|
|
113
129
|
"get" => {
|
|
114
130
|
"summary" => "Heartbeat", "tags" => ["Info"],
|
|
@@ -337,11 +353,11 @@ module Api
|
|
|
337
353
|
|
|
338
354
|
### Info & utility endpoints
|
|
339
355
|
|
|
340
|
-
`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).
|
|
341
357
|
|
|
342
358
|
### Raw SQL escape hatch
|
|
343
359
|
|
|
344
|
-
`GET|POST /raw/sql` — SELECT
|
|
360
|
+
`GET|POST /raw/sql` — one plain SELECT, READ ONLY with limits; returns plain JSON array (not JSON:API); 422/413 with `{error, reason}` on refusal.
|
|
345
361
|
MD
|
|
346
362
|
end
|
|
347
363
|
end
|
|
@@ -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|
|
data/lib/model_driven_api.rb
CHANGED
|
@@ -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
|
data/lib/safe_sql_executor.rb
CHANGED
|
@@ -1,20 +1,238 @@
|
|
|
1
|
+
require "pg_query"
|
|
2
|
+
require "securerandom"
|
|
3
|
+
|
|
4
|
+
# Runs the SQL string of POST /api/v2|v3/raw/sql, sent by any authenticated user (host ADR 0048,
|
|
5
|
+
# Odoo #5835). What makes it safe is not who may call it but what the query can do:
|
|
6
|
+
#
|
|
7
|
+
# 1. PostgreSQL's own parser (pg_query) accepts exactly one plain SELECT: no INTO, no
|
|
8
|
+
# FOR UPDATE/SHARE, no INSERT/UPDATE/DELETE/MERGE anywhere in the tree (CTEs included), and none
|
|
9
|
+
# of DENIED_FUNCTIONS. It is the second line, there for a clear 422: SQL hidden in strings
|
|
10
|
+
# (query_to_xml) escapes any parser.
|
|
11
|
+
# 2. The query runs in a transaction of its own: READ ONLY, statement/lock timeouts, work_mem and
|
|
12
|
+
# temp_file_limit, through select_all (one statement over exec_params, never execute), and is
|
|
13
|
+
# always rolled back. Session advisory locks survive a rollback, so pg_advisory_unlock_all()
|
|
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.
|
|
17
|
+
#
|
|
18
|
+
# Errors never carry PostgreSQL's message: the caller gets Rejected/Failed with a reason, the
|
|
19
|
+
# details go to the Rails log tagged with the correlation id (the request id).
|
|
20
|
+
#
|
|
21
|
+
# RAW_SQL_ENFORCE=false (rollout switch, per installation): a rejection (parser, size, privileges,
|
|
22
|
+
# READ ONLY) is logged as IntegrationLog :warning (when the host has that model) and the query runs
|
|
23
|
+
# again the old way, so a frontend not verified yet keeps working while the logs show what the new
|
|
24
|
+
# rules would break. Failures (timeout, SQL error, oversize result) are never rerun: the old way
|
|
25
|
+
# would only run an expensive query again without any limit.
|
|
1
26
|
module SafeSqlExecutor
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
27
|
+
# The response body's "error" is +kind+; "reason" says why, without schema details.
|
|
28
|
+
class Error < StandardError
|
|
29
|
+
attr_reader :reason, :sqlstate
|
|
30
|
+
|
|
31
|
+
def initialize(reason, sqlstate: nil)
|
|
32
|
+
@reason = reason
|
|
33
|
+
@sqlstate = sqlstate
|
|
34
|
+
super(reason)
|
|
35
|
+
end
|
|
5
36
|
|
|
6
|
-
|
|
7
|
-
|
|
37
|
+
def as_json(*)
|
|
38
|
+
{"error" => kind, "reason" => reason, "sqlstate" => sqlstate}.compact
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# The v3 status; v2 answers 400 for every error.
|
|
42
|
+
def http_status
|
|
43
|
+
422
|
|
44
|
+
end
|
|
8
45
|
end
|
|
9
46
|
|
|
10
|
-
|
|
47
|
+
# The query is not allowed: refused by the parser, by its size, or by the database's privileges.
|
|
48
|
+
class Rejected < Error
|
|
49
|
+
def kind
|
|
50
|
+
"raw_sql_rejected"
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# An allowed query that could not complete: timeout, SQL error, nested call.
|
|
55
|
+
class Failed < Error
|
|
56
|
+
def kind
|
|
57
|
+
"raw_sql_failed"
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# The rows exceed RAW_SQL_MAX_RESULT_BYTES.
|
|
62
|
+
class ResultTooLarge < Failed
|
|
63
|
+
def initialize
|
|
64
|
+
super("result_too_large")
|
|
65
|
+
end
|
|
11
66
|
|
|
12
|
-
|
|
13
|
-
|
|
67
|
+
def http_status
|
|
68
|
+
413
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# Called with no or the wrong arguments these still have effects that READ ONLY doesn't stop
|
|
73
|
+
# or that outlive the transaction (host research raw-sql-safe-execution.md §2.2, §2.4).
|
|
74
|
+
DENIED_FUNCTIONS = %w[
|
|
75
|
+
set_config
|
|
76
|
+
pg_advisory_lock pg_advisory_lock_shared pg_try_advisory_lock pg_try_advisory_lock_shared
|
|
77
|
+
pg_advisory_unlock pg_advisory_unlock_shared pg_advisory_unlock_all
|
|
78
|
+
lo_create lo_creat lo_open lo_write lowrite lo_put lo_from_bytea lo_unlink lo_truncate
|
|
79
|
+
lo_truncate64 lo_import lo_export
|
|
80
|
+
pg_terminate_backend pg_cancel_backend
|
|
81
|
+
pg_sleep pg_sleep_for pg_sleep_until
|
|
82
|
+
pg_notify
|
|
83
|
+
].freeze
|
|
84
|
+
|
|
85
|
+
DML_NODES = [PgQuery::InsertStmt, PgQuery::UpdateStmt, PgQuery::DeleteStmt, PgQuery::MergeStmt].freeze
|
|
86
|
+
|
|
87
|
+
# Each overridable with RAW_SQL_<NAME> (ADR 0048 §6).
|
|
88
|
+
DEFAULTS = {
|
|
89
|
+
statement_timeout: "15s",
|
|
90
|
+
lock_timeout: "1s",
|
|
91
|
+
work_mem: "16MB",
|
|
92
|
+
temp_file_limit: "256MB",
|
|
93
|
+
max_query_bytes: 100 * 1024,
|
|
94
|
+
max_result_bytes: 10 * 1024 * 1024
|
|
95
|
+
}.freeze
|
|
96
|
+
|
|
97
|
+
# SQLSTATEs that mean "not allowed" rather than "broken query": insufficient privilege,
|
|
98
|
+
# read-only transaction.
|
|
99
|
+
NOT_PERMITTED = %w[42501 25006].freeze
|
|
100
|
+
# query_canceled (statement_timeout), lock_not_available (lock_timeout).
|
|
101
|
+
TIMEOUT = %w[57014 55P03].freeze
|
|
102
|
+
|
|
103
|
+
module_function
|
|
104
|
+
|
|
105
|
+
# Rows of the query as an Array of Hashes. Raises Rejected or Failed; with RAW_SQL_ENFORCE=false
|
|
106
|
+
# the legacy path's errors (ArgumentError, ActiveRecord::StatementInvalid) come through as before.
|
|
107
|
+
def execute_select(query, correlation_id: nil)
|
|
108
|
+
correlation_id ||= SecureRandom.uuid
|
|
109
|
+
validate!(query)
|
|
110
|
+
run(query, correlation_id)
|
|
111
|
+
rescue Error => e
|
|
112
|
+
Rails.logger.warn("[raw_sql #{correlation_id}] #{e.kind} #{e.reason}")
|
|
113
|
+
raise if e.is_a?(Failed) || enforce?
|
|
114
|
+
|
|
115
|
+
log_unenforced(query, e, correlation_id)
|
|
116
|
+
legacy_execute(query)
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
def enforce?
|
|
120
|
+
ENV.fetch("RAW_SQL_ENFORCE", "true").strip.downcase != "false"
|
|
121
|
+
end
|
|
14
122
|
|
|
15
|
-
|
|
16
|
-
|
|
123
|
+
# RAW_SQL_<NAME>, or the default. A byte cap that isn't an integer falls back to the default (with
|
|
124
|
+
# a warning) rather than break every query; a bad GUC value is PostgreSQL's to refuse.
|
|
125
|
+
def setting(name)
|
|
126
|
+
default = DEFAULTS.fetch(name)
|
|
127
|
+
value = ENV["RAW_SQL_#{name.to_s.upcase}"].presence
|
|
128
|
+
return default if value.nil?
|
|
129
|
+
return value unless default.is_a?(Integer)
|
|
130
|
+
|
|
131
|
+
Integer(value, 10)
|
|
132
|
+
rescue ArgumentError
|
|
133
|
+
Rails.logger.warn("[raw_sql] RAW_SQL_#{name.to_s.upcase}=#{value.inspect} is not a byte count, using #{default}")
|
|
134
|
+
default
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def validate!(query)
|
|
138
|
+
raise Rejected, "query_too_large" if query.bytesize > setting(:max_query_bytes)
|
|
139
|
+
|
|
140
|
+
parsed = PgQuery.parse(query)
|
|
141
|
+
stmts = parsed.tree.stmts
|
|
142
|
+
raise Rejected, "only_single_select" unless stmts.size == 1 && stmts.first.stmt.select_stmt
|
|
143
|
+
|
|
144
|
+
parsed.walk! do |node|
|
|
145
|
+
case node
|
|
146
|
+
when *DML_NODES
|
|
147
|
+
raise Rejected, "data_modifying_statement"
|
|
148
|
+
when PgQuery::SelectStmt
|
|
149
|
+
raise Rejected, "data_modifying_statement" if node.into_clause
|
|
150
|
+
raise Rejected, "locking_clause" if node.locking_clause.any?
|
|
151
|
+
when PgQuery::FuncCall
|
|
152
|
+
name = node.funcname.last&.string&.sval.to_s.downcase
|
|
153
|
+
raise Rejected, "function_not_allowed" if DENIED_FUNCTIONS.include?(name)
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
rescue PgQuery::ParseError
|
|
157
|
+
raise Rejected, "syntax_error"
|
|
158
|
+
end
|
|
159
|
+
|
|
160
|
+
def run(query, correlation_id)
|
|
161
|
+
conn = ActiveRecord::Base.connection
|
|
162
|
+
# A nested call would only get a savepoint: READ ONLY and the limits must own the transaction.
|
|
163
|
+
raise Failed, "nested_transaction" if conn.transaction_open?
|
|
164
|
+
|
|
165
|
+
rows = nil
|
|
166
|
+
begin
|
|
167
|
+
conn.transaction do
|
|
168
|
+
conn.execute("SET TRANSACTION READ ONLY")
|
|
169
|
+
conn.execute("SET LOCAL statement_timeout = #{conn.quote(setting(:statement_timeout))}")
|
|
170
|
+
conn.execute("SET LOCAL lock_timeout = #{conn.quote(setting(:lock_timeout))}")
|
|
171
|
+
conn.execute("SET LOCAL work_mem = #{conn.quote(setting(:work_mem))}")
|
|
172
|
+
# Superuser-only (PGC_SUSET): on an installation where the app isn't superuser it is skipped.
|
|
173
|
+
if RawSqlGrants.superuser?(conn)
|
|
174
|
+
conn.execute("SET LOCAL temp_file_limit = #{conn.quote(setting(:temp_file_limit))}")
|
|
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)
|
|
179
|
+
rows = conn.select_all(query, "RawSql").to_a
|
|
180
|
+
raise ActiveRecord::Rollback
|
|
181
|
+
end
|
|
182
|
+
rescue ActiveRecord::StatementInvalid => e
|
|
183
|
+
raise translate(e, correlation_id)
|
|
184
|
+
ensure
|
|
185
|
+
release_advisory_locks(conn, correlation_id)
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
check_result_size!(rows)
|
|
189
|
+
rows
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
def check_result_size!(rows)
|
|
193
|
+
size = rows.sum { |row| row.sum { |_, value| value.to_s.bytesize } }
|
|
194
|
+
raise ResultTooLarge if size > setting(:max_result_bytes)
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
# Session advisory locks survive the rollback. Guarded: on a broken connection its own error must
|
|
198
|
+
# not replace the query's (whose PostgreSQL message would then reach the controller).
|
|
199
|
+
def release_advisory_locks(conn, correlation_id)
|
|
200
|
+
conn.select_value("SELECT pg_advisory_unlock_all()")
|
|
201
|
+
rescue ActiveRecord::ActiveRecordError => e
|
|
202
|
+
Rails.logger.error("[raw_sql #{correlation_id}] pg_advisory_unlock_all failed: #{e.class}")
|
|
203
|
+
end
|
|
204
|
+
|
|
205
|
+
def translate(error, correlation_id)
|
|
206
|
+
sqlstate = error.cause.respond_to?(:result) ? error.cause.result&.error_field(PG::Result::PG_DIAG_SQLSTATE) : nil
|
|
207
|
+
Rails.logger.warn("[raw_sql #{correlation_id}] #{sqlstate} #{error.cause&.message || error.message}")
|
|
208
|
+
if NOT_PERMITTED.include?(sqlstate)
|
|
209
|
+
Rejected.new("not_permitted")
|
|
210
|
+
elsif TIMEOUT.include?(sqlstate)
|
|
211
|
+
Failed.new("timeout")
|
|
212
|
+
else
|
|
213
|
+
Failed.new("query_error", sqlstate: sqlstate)
|
|
214
|
+
end
|
|
215
|
+
end
|
|
216
|
+
|
|
217
|
+
def log_unenforced(query, error, correlation_id)
|
|
218
|
+
Rails.logger.warn("[raw_sql #{correlation_id}] RAW_SQL_ENFORCE=false: #{error.kind} #{error.reason}, running it the old way")
|
|
219
|
+
return unless defined?(::IntegrationLog)
|
|
220
|
+
|
|
221
|
+
::IntegrationLog.create!(
|
|
222
|
+
severity: "warning",
|
|
223
|
+
description: "raw/sql: #{error.kind} (#{error.reason}), run anyway because RAW_SQL_ENFORCE=false",
|
|
224
|
+
data: {correlation_id: correlation_id, reason: error.reason, query: query.truncate(10_000)}
|
|
225
|
+
)
|
|
226
|
+
rescue => e
|
|
227
|
+
Rails.logger.error("[raw_sql #{correlation_id}] IntegrationLog not written: #{e.class}")
|
|
228
|
+
end
|
|
229
|
+
|
|
230
|
+
# The pre-ADR 0048 behaviour, reached only with RAW_SQL_ENFORCE=false.
|
|
231
|
+
def legacy_execute(query)
|
|
232
|
+
unless query.strip.gsub(/\s+/, " ").upcase.match?(/^(WITH .+)?SELECT /)
|
|
17
233
|
raise ArgumentError, "Only SELECT queries (including with CTEs) are allowed"
|
|
18
234
|
end
|
|
235
|
+
|
|
236
|
+
ActiveRecord::Base.connection.execute(query).to_a
|
|
19
237
|
end
|
|
20
|
-
end
|
|
238
|
+
end
|
|
@@ -1,4 +1,22 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
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.
|
|
4
|
+
version: 3.16.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Gabriele Tassoni
|
|
@@ -142,6 +142,26 @@ dependencies:
|
|
|
142
142
|
- - "~>"
|
|
143
143
|
- !ruby/object:Gem::Version
|
|
144
144
|
version: '9.0'
|
|
145
|
+
- !ruby/object:Gem::Dependency
|
|
146
|
+
name: pg_query
|
|
147
|
+
requirement: !ruby/object:Gem::Requirement
|
|
148
|
+
requirements:
|
|
149
|
+
- - ">="
|
|
150
|
+
- !ruby/object:Gem::Version
|
|
151
|
+
version: 6.2.5
|
|
152
|
+
- - "<"
|
|
153
|
+
- !ruby/object:Gem::Version
|
|
154
|
+
version: '7'
|
|
155
|
+
type: :runtime
|
|
156
|
+
prerelease: false
|
|
157
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
158
|
+
requirements:
|
|
159
|
+
- - ">="
|
|
160
|
+
- !ruby/object:Gem::Version
|
|
161
|
+
version: 6.2.5
|
|
162
|
+
- - "<"
|
|
163
|
+
- !ruby/object:Gem::Version
|
|
164
|
+
version: '7'
|
|
145
165
|
- !ruby/object:Gem::Dependency
|
|
146
166
|
name: pg
|
|
147
167
|
requirement: !ruby/object:Gem::Requirement
|
|
@@ -204,7 +224,6 @@ files:
|
|
|
204
224
|
- app/controllers/api/v2/raw_controller.rb
|
|
205
225
|
- app/controllers/api/v2/users_controller.rb
|
|
206
226
|
- app/controllers/api/v3/application_controller.rb
|
|
207
|
-
- app/controllers/api/v3/auth/oauth_controller.rb
|
|
208
227
|
- app/controllers/api/v3/authentication_controller.rb
|
|
209
228
|
- app/controllers/api/v3/info_controller.rb
|
|
210
229
|
- app/controllers/api/v3/raw_controller.rb
|
|
@@ -224,6 +243,7 @@ files:
|
|
|
224
243
|
- config/routes.rb
|
|
225
244
|
- db/migrate/20210519145438_create_used_tokens.rb
|
|
226
245
|
- db/migrate/20210528111450_rename_valid_to_is_valid_in_used_token.rb
|
|
246
|
+
- db/migrate/20261125120000_apply_thecore_raw_grants.rb
|
|
227
247
|
- lib/api/custom_action_dispatcher.rb
|
|
228
248
|
- lib/api/model_resolver.rb
|
|
229
249
|
- lib/api/open_api/base.rb
|
|
@@ -244,6 +264,7 @@ files:
|
|
|
244
264
|
- lib/model_driven_api/engine.rb
|
|
245
265
|
- lib/model_driven_api/version.rb
|
|
246
266
|
- lib/non_crud_endpoints.rb
|
|
267
|
+
- lib/raw_sql_grants.rb
|
|
247
268
|
- lib/safe_sql_executor.rb
|
|
248
269
|
- lib/tasks/model_driven_api_tasks.rake
|
|
249
270
|
homepage: https://github.com/gabrieletassoni/model_driven_api
|