model_driven_api 3.14.1 → 3.15.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 +16 -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/raw_controller.rb +14 -13
- data/app/controllers/api/v3/raw_controller.rb +10 -6
- data/config/routes.rb +0 -7
- data/lib/api/open_api/v2.rb +8 -2
- data/lib/api/open_api/v3.rb +14 -5
- data/lib/model_driven_api/version.rb +1 -1
- data/lib/safe_sql_executor.rb +224 -11
- metadata +21 -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: 9553ee66372d69d5fbe182a01d009ef9e5dc950a78bbda880b4a7ed7cd0da3b5
|
|
4
|
+
data.tar.gz: ee749ca1d1cc97ec5d7b602f96e0f76d71f4e1cfc23dcacec2cb3a869c672c09
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: d6815fb7e5fa7729645686b3ff89e2142864835b3b0236c86ae814bb85459eb6098f3b433b09a24a91e4321aae703c0cb11df8ea351ab9b2366b08aa0b12ec8b
|
|
7
|
+
data.tar.gz: 64abdba4f33449541eba0add552ad85be0a4d55259461215853ef826837aa46e8d5905cba9dde58bf9e48cf25b4178bbca9e6e4a2fd6fb55579f13aa376835dd
|
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,19 @@ 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.
|
|
471
470
|
|
|
472
471
|
### v2 — requires `result` key
|
|
473
472
|
|
|
@@ -477,7 +476,7 @@ Authorization: Bearer <jwt>
|
|
|
477
476
|
Content-Type: application/json
|
|
478
477
|
|
|
479
478
|
{
|
|
480
|
-
"query": "SELECT json_agg(
|
|
479
|
+
"query": "SELECT json_agg(r) AS result FROM (SELECT id, name FROM roles) r"
|
|
481
480
|
}
|
|
482
481
|
```
|
|
483
482
|
|
|
@@ -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
|
|
@@ -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
|
|
@@ -61,7 +55,6 @@ Rails.application.routes.draw do
|
|
|
61
55
|
match ":provider/callback", to: "oauth#callback", via: [:get, :post]
|
|
62
56
|
get :failure, to: "oauth#failure"
|
|
63
57
|
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
58
|
end
|
|
66
59
|
end
|
|
67
60
|
|
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
|
},
|
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
|
},
|
|
@@ -341,7 +350,7 @@ module Api
|
|
|
341
350
|
|
|
342
351
|
### Raw SQL escape hatch
|
|
343
352
|
|
|
344
|
-
`GET|POST /raw/sql` — SELECT
|
|
353
|
+
`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
354
|
MD
|
|
346
355
|
end
|
|
347
356
|
end
|
data/lib/safe_sql_executor.rb
CHANGED
|
@@ -1,20 +1,233 @@
|
|
|
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. The database role that hides secrets comes with Odoo #6093.
|
|
15
|
+
#
|
|
16
|
+
# Errors never carry PostgreSQL's message: the caller gets Rejected/Failed with a reason, the
|
|
17
|
+
# details go to the Rails log tagged with the correlation id (the request id).
|
|
18
|
+
#
|
|
19
|
+
# RAW_SQL_ENFORCE=false (rollout switch, per installation): a rejection (parser, size, privileges,
|
|
20
|
+
# READ ONLY) is logged as IntegrationLog :warning (when the host has that model) and the query runs
|
|
21
|
+
# again the old way, so a frontend not verified yet keeps working while the logs show what the new
|
|
22
|
+
# rules would break. Failures (timeout, SQL error, oversize result) are never rerun: the old way
|
|
23
|
+
# would only run an expensive query again without any limit.
|
|
1
24
|
module SafeSqlExecutor
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
25
|
+
# The response body's "error" is +kind+; "reason" says why, without schema details.
|
|
26
|
+
class Error < StandardError
|
|
27
|
+
attr_reader :reason, :sqlstate
|
|
28
|
+
|
|
29
|
+
def initialize(reason, sqlstate: nil)
|
|
30
|
+
@reason = reason
|
|
31
|
+
@sqlstate = sqlstate
|
|
32
|
+
super(reason)
|
|
33
|
+
end
|
|
5
34
|
|
|
6
|
-
|
|
7
|
-
|
|
35
|
+
def as_json(*)
|
|
36
|
+
{"error" => kind, "reason" => reason, "sqlstate" => sqlstate}.compact
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# The v3 status; v2 answers 400 for every error.
|
|
40
|
+
def http_status
|
|
41
|
+
422
|
|
42
|
+
end
|
|
8
43
|
end
|
|
9
44
|
|
|
10
|
-
|
|
45
|
+
# The query is not allowed: refused by the parser, by its size, or by the database's privileges.
|
|
46
|
+
class Rejected < Error
|
|
47
|
+
def kind
|
|
48
|
+
"raw_sql_rejected"
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# An allowed query that could not complete: timeout, SQL error, nested call.
|
|
53
|
+
class Failed < Error
|
|
54
|
+
def kind
|
|
55
|
+
"raw_sql_failed"
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# The rows exceed RAW_SQL_MAX_RESULT_BYTES.
|
|
60
|
+
class ResultTooLarge < Failed
|
|
61
|
+
def initialize
|
|
62
|
+
super("result_too_large")
|
|
63
|
+
end
|
|
11
64
|
|
|
12
|
-
|
|
13
|
-
|
|
65
|
+
def http_status
|
|
66
|
+
413
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# Called with no or the wrong arguments these still have effects that READ ONLY doesn't stop
|
|
71
|
+
# or that outlive the transaction (host research raw-sql-safe-execution.md §2.2, §2.4).
|
|
72
|
+
DENIED_FUNCTIONS = %w[
|
|
73
|
+
set_config
|
|
74
|
+
pg_advisory_lock pg_advisory_lock_shared pg_try_advisory_lock pg_try_advisory_lock_shared
|
|
75
|
+
pg_advisory_unlock pg_advisory_unlock_shared pg_advisory_unlock_all
|
|
76
|
+
lo_create lo_creat lo_open lo_write lowrite lo_put lo_from_bytea lo_unlink lo_truncate
|
|
77
|
+
lo_truncate64 lo_import lo_export
|
|
78
|
+
pg_terminate_backend pg_cancel_backend
|
|
79
|
+
pg_sleep pg_sleep_for pg_sleep_until
|
|
80
|
+
pg_notify
|
|
81
|
+
].freeze
|
|
82
|
+
|
|
83
|
+
DML_NODES = [PgQuery::InsertStmt, PgQuery::UpdateStmt, PgQuery::DeleteStmt, PgQuery::MergeStmt].freeze
|
|
84
|
+
|
|
85
|
+
# Each overridable with RAW_SQL_<NAME> (ADR 0048 §6).
|
|
86
|
+
DEFAULTS = {
|
|
87
|
+
statement_timeout: "15s",
|
|
88
|
+
lock_timeout: "1s",
|
|
89
|
+
work_mem: "16MB",
|
|
90
|
+
temp_file_limit: "256MB",
|
|
91
|
+
max_query_bytes: 100 * 1024,
|
|
92
|
+
max_result_bytes: 10 * 1024 * 1024
|
|
93
|
+
}.freeze
|
|
94
|
+
|
|
95
|
+
# SQLSTATEs that mean "not allowed" rather than "broken query": insufficient privilege,
|
|
96
|
+
# read-only transaction.
|
|
97
|
+
NOT_PERMITTED = %w[42501 25006].freeze
|
|
98
|
+
# query_canceled (statement_timeout), lock_not_available (lock_timeout).
|
|
99
|
+
TIMEOUT = %w[57014 55P03].freeze
|
|
100
|
+
|
|
101
|
+
module_function
|
|
102
|
+
|
|
103
|
+
# Rows of the query as an Array of Hashes. Raises Rejected or Failed; with RAW_SQL_ENFORCE=false
|
|
104
|
+
# the legacy path's errors (ArgumentError, ActiveRecord::StatementInvalid) come through as before.
|
|
105
|
+
def execute_select(query, correlation_id: nil)
|
|
106
|
+
correlation_id ||= SecureRandom.uuid
|
|
107
|
+
validate!(query)
|
|
108
|
+
run(query, correlation_id)
|
|
109
|
+
rescue Error => e
|
|
110
|
+
Rails.logger.warn("[raw_sql #{correlation_id}] #{e.kind} #{e.reason}")
|
|
111
|
+
raise if e.is_a?(Failed) || enforce?
|
|
112
|
+
|
|
113
|
+
log_unenforced(query, e, correlation_id)
|
|
114
|
+
legacy_execute(query)
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def enforce?
|
|
118
|
+
ENV.fetch("RAW_SQL_ENFORCE", "true").strip.downcase != "false"
|
|
119
|
+
end
|
|
14
120
|
|
|
15
|
-
|
|
16
|
-
|
|
121
|
+
# RAW_SQL_<NAME>, or the default. A byte cap that isn't an integer falls back to the default (with
|
|
122
|
+
# a warning) rather than break every query; a bad GUC value is PostgreSQL's to refuse.
|
|
123
|
+
def setting(name)
|
|
124
|
+
default = DEFAULTS.fetch(name)
|
|
125
|
+
value = ENV["RAW_SQL_#{name.to_s.upcase}"].presence
|
|
126
|
+
return default if value.nil?
|
|
127
|
+
return value unless default.is_a?(Integer)
|
|
128
|
+
|
|
129
|
+
Integer(value, 10)
|
|
130
|
+
rescue ArgumentError
|
|
131
|
+
Rails.logger.warn("[raw_sql] RAW_SQL_#{name.to_s.upcase}=#{value.inspect} is not a byte count, using #{default}")
|
|
132
|
+
default
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def validate!(query)
|
|
136
|
+
raise Rejected, "query_too_large" if query.bytesize > setting(:max_query_bytes)
|
|
137
|
+
|
|
138
|
+
parsed = PgQuery.parse(query)
|
|
139
|
+
stmts = parsed.tree.stmts
|
|
140
|
+
raise Rejected, "only_single_select" unless stmts.size == 1 && stmts.first.stmt.select_stmt
|
|
141
|
+
|
|
142
|
+
parsed.walk! do |node|
|
|
143
|
+
case node
|
|
144
|
+
when *DML_NODES
|
|
145
|
+
raise Rejected, "data_modifying_statement"
|
|
146
|
+
when PgQuery::SelectStmt
|
|
147
|
+
raise Rejected, "data_modifying_statement" if node.into_clause
|
|
148
|
+
raise Rejected, "locking_clause" if node.locking_clause.any?
|
|
149
|
+
when PgQuery::FuncCall
|
|
150
|
+
name = node.funcname.last&.string&.sval.to_s.downcase
|
|
151
|
+
raise Rejected, "function_not_allowed" if DENIED_FUNCTIONS.include?(name)
|
|
152
|
+
end
|
|
153
|
+
end
|
|
154
|
+
rescue PgQuery::ParseError
|
|
155
|
+
raise Rejected, "syntax_error"
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
def run(query, correlation_id)
|
|
159
|
+
conn = ActiveRecord::Base.connection
|
|
160
|
+
# A nested call would only get a savepoint: READ ONLY and the limits must own the transaction.
|
|
161
|
+
raise Failed, "nested_transaction" if conn.transaction_open?
|
|
162
|
+
|
|
163
|
+
rows = nil
|
|
164
|
+
begin
|
|
165
|
+
conn.transaction do
|
|
166
|
+
conn.execute("SET TRANSACTION READ ONLY")
|
|
167
|
+
conn.execute("SET LOCAL statement_timeout = #{conn.quote(setting(:statement_timeout))}")
|
|
168
|
+
conn.execute("SET LOCAL lock_timeout = #{conn.quote(setting(:lock_timeout))}")
|
|
169
|
+
conn.execute("SET LOCAL work_mem = #{conn.quote(setting(:work_mem))}")
|
|
170
|
+
# 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"
|
|
172
|
+
conn.execute("SET LOCAL temp_file_limit = #{conn.quote(setting(:temp_file_limit))}")
|
|
173
|
+
end
|
|
174
|
+
rows = conn.select_all(query, "RawSql").to_a
|
|
175
|
+
raise ActiveRecord::Rollback
|
|
176
|
+
end
|
|
177
|
+
rescue ActiveRecord::StatementInvalid => e
|
|
178
|
+
raise translate(e, correlation_id)
|
|
179
|
+
ensure
|
|
180
|
+
release_advisory_locks(conn, correlation_id)
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
check_result_size!(rows)
|
|
184
|
+
rows
|
|
185
|
+
end
|
|
186
|
+
|
|
187
|
+
def check_result_size!(rows)
|
|
188
|
+
size = rows.sum { |row| row.sum { |_, value| value.to_s.bytesize } }
|
|
189
|
+
raise ResultTooLarge if size > setting(:max_result_bytes)
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
# Session advisory locks survive the rollback. Guarded: on a broken connection its own error must
|
|
193
|
+
# not replace the query's (whose PostgreSQL message would then reach the controller).
|
|
194
|
+
def release_advisory_locks(conn, correlation_id)
|
|
195
|
+
conn.select_value("SELECT pg_advisory_unlock_all()")
|
|
196
|
+
rescue ActiveRecord::ActiveRecordError => e
|
|
197
|
+
Rails.logger.error("[raw_sql #{correlation_id}] pg_advisory_unlock_all failed: #{e.class}")
|
|
198
|
+
end
|
|
199
|
+
|
|
200
|
+
def translate(error, correlation_id)
|
|
201
|
+
sqlstate = error.cause.respond_to?(:result) ? error.cause.result&.error_field(PG::Result::PG_DIAG_SQLSTATE) : nil
|
|
202
|
+
Rails.logger.warn("[raw_sql #{correlation_id}] #{sqlstate} #{error.cause&.message || error.message}")
|
|
203
|
+
if NOT_PERMITTED.include?(sqlstate)
|
|
204
|
+
Rejected.new("not_permitted")
|
|
205
|
+
elsif TIMEOUT.include?(sqlstate)
|
|
206
|
+
Failed.new("timeout")
|
|
207
|
+
else
|
|
208
|
+
Failed.new("query_error", sqlstate: sqlstate)
|
|
209
|
+
end
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
def log_unenforced(query, error, correlation_id)
|
|
213
|
+
Rails.logger.warn("[raw_sql #{correlation_id}] RAW_SQL_ENFORCE=false: #{error.kind} #{error.reason}, running it the old way")
|
|
214
|
+
return unless defined?(::IntegrationLog)
|
|
215
|
+
|
|
216
|
+
::IntegrationLog.create!(
|
|
217
|
+
severity: "warning",
|
|
218
|
+
description: "raw/sql: #{error.kind} (#{error.reason}), run anyway because RAW_SQL_ENFORCE=false",
|
|
219
|
+
data: {correlation_id: correlation_id, reason: error.reason, query: query.truncate(10_000)}
|
|
220
|
+
)
|
|
221
|
+
rescue => e
|
|
222
|
+
Rails.logger.error("[raw_sql #{correlation_id}] IntegrationLog not written: #{e.class}")
|
|
223
|
+
end
|
|
224
|
+
|
|
225
|
+
# The pre-ADR 0048 behaviour, reached only with RAW_SQL_ENFORCE=false.
|
|
226
|
+
def legacy_execute(query)
|
|
227
|
+
unless query.strip.gsub(/\s+/, " ").upcase.match?(/^(WITH .+)?SELECT /)
|
|
17
228
|
raise ArgumentError, "Only SELECT queries (including with CTEs) are allowed"
|
|
18
229
|
end
|
|
230
|
+
|
|
231
|
+
ActiveRecord::Base.connection.execute(query).to_a
|
|
19
232
|
end
|
|
20
|
-
end
|
|
233
|
+
end
|
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.15.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
|