rails_ai_admin 0.4.1 → 0.5.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/CHANGELOG.md +64 -0
- data/README.md +4 -9
- data/SECURITY.md +1 -1
- data/app/assets/builds/rails_ai_admin.js +5 -5
- data/app/controllers/rails_ai_admin/application_controller.rb +19 -6
- data/app/controllers/rails_ai_admin/assistant_controller.rb +20 -7
- data/app/controllers/rails_ai_admin/audit_controller.rb +5 -1
- data/app/controllers/rails_ai_admin/bulk_changes_controller.rb +26 -6
- data/app/controllers/rails_ai_admin/dashboard_controller.rb +3 -2
- data/app/controllers/rails_ai_admin/deleted_records_controller.rb +12 -4
- data/app/controllers/rails_ai_admin/files_controller.rb +16 -4
- data/app/controllers/rails_ai_admin/mcp_controller.rb +30 -4
- data/app/controllers/rails_ai_admin/mcp_tokens_controller.rb +4 -2
- data/app/controllers/rails_ai_admin/operations_controller.rb +5 -2
- data/app/controllers/rails_ai_admin/resources_controller.rb +44 -5
- data/app/controllers/rails_ai_admin/selections_controller.rb +41 -5
- data/app/helpers/rails_ai_admin/assistant_helper.rb +3 -1
- data/app/helpers/rails_ai_admin/fields_helper.rb +36 -7
- data/app/helpers/rails_ai_admin/history_helper.rb +1 -1
- data/app/views/layouts/rails_ai_admin/application.html.erb +1 -0
- data/app/views/layouts/rails_ai_admin/frame.html.erb +1 -1
- data/app/views/layouts/rails_ai_admin/status.html.erb +2 -2
- data/app/views/rails_ai_admin/assistant/_transcript.html.erb +5 -1
- data/app/views/rails_ai_admin/audit/index.html.erb +1 -1
- data/app/views/rails_ai_admin/deleted_records/index.html.erb +3 -2
- data/app/views/rails_ai_admin/fields/_input.html.erb +2 -1
- data/app/views/rails_ai_admin/selections/confirm_destroy.html.erb +1 -0
- data/config/locales/en.yml +2 -0
- data/db/assistant_migrate/20261103000001_create_rails_ai_admin_assistant.rb +1 -0
- data/db/migrate/20261122000001_add_missing_indexes_to_rails_ai_admin_tables.rb +12 -0
- data/lib/generators/rails_ai_admin/assistant/assistant_generator.rb +4 -1
- data/lib/generators/rails_ai_admin/assistant/templates/admin_assistant.rb +6 -0
- data/lib/generators/rails_ai_admin/assistant/templates/assistant_eval.yml +25 -0
- data/lib/generators/rails_ai_admin/install/templates/admin_context_devise.rb.tt +2 -1
- data/lib/generators/rails_ai_admin/install/templates/admin_context_rails.rb.tt +5 -2
- data/lib/rails_ai_admin/assistant/budget.rb +4 -2
- data/lib/rails_ai_admin/assistant/coordinator.rb +18 -4
- data/lib/rails_ai_admin/assistant/evaluation.rb +124 -0
- data/lib/rails_ai_admin/assistant/records.rb +2 -1
- data/lib/rails_ai_admin/assistant/retention.rb +12 -1
- data/lib/rails_ai_admin/assistant/runtime.rb +49 -1
- data/lib/rails_ai_admin/assistant/tools.rb +58 -18
- data/lib/rails_ai_admin/assistant.rb +1 -0
- data/lib/rails_ai_admin/authorization/access.rb +34 -23
- data/lib/rails_ai_admin/authorization/pundit_adapter.rb +6 -3
- data/lib/rails_ai_admin/collections/dispatcher.rb +3 -3
- data/lib/rails_ai_admin/collections/queries.rb +1 -1
- data/lib/rails_ai_admin/configuration.rb +39 -8
- data/lib/rails_ai_admin/doctor.rb +44 -9
- data/lib/rails_ai_admin/field.rb +37 -22
- data/lib/rails_ai_admin/fields/association.rb +27 -10
- data/lib/rails_ai_admin/fields/type.rb +1 -1
- data/lib/rails_ai_admin/forms/plan.rb +4 -2
- data/lib/rails_ai_admin/input_schema.rb +4 -4
- data/lib/rails_ai_admin/integrations/propose_operation.rb +18 -4
- data/lib/rails_ai_admin/integrations/tool_views.rb +29 -3
- data/lib/rails_ai_admin/mcp.rb +23 -13
- data/lib/rails_ai_admin/navigation/list_state.rb +3 -3
- data/lib/rails_ai_admin/navigation/saved_views.rb +6 -5
- data/lib/rails_ai_admin/operations/restore.rb +25 -4
- data/lib/rails_ai_admin/operations/runner.rb +51 -15
- data/lib/rails_ai_admin/outbox/dispatcher.rb +6 -2
- data/lib/rails_ai_admin/presentation/association_panel.rb +6 -6
- data/lib/rails_ai_admin/presentation/audit_log.rb +8 -3
- data/lib/rails_ai_admin/presentation/csv_export.rb +21 -8
- data/lib/rails_ai_admin/presentation/csv_import.rb +9 -1
- data/lib/rails_ai_admin/presentation/dashboard.rb +5 -2
- data/lib/rails_ai_admin/presentation/history.rb +1 -1
- data/lib/rails_ai_admin/prune.rb +16 -5
- data/lib/rails_ai_admin/queries/list.rb +138 -38
- data/lib/rails_ai_admin/record_version.rb +1 -1
- data/lib/rails_ai_admin/registry.rb +5 -0
- data/lib/rails_ai_admin/request_log_filter.rb +4 -2
- data/lib/rails_ai_admin/resource.rb +4 -0
- data/lib/rails_ai_admin/schema_suggestions.rb +13 -5
- data/lib/rails_ai_admin/templates/catalog.rb +4 -2
- data/lib/rails_ai_admin/templates/inspector.rb +6 -2
- data/lib/rails_ai_admin/templates/safe_paths.rb +2 -1
- data/lib/rails_ai_admin/version.rb +1 -1
- data/lib/rails_ai_admin/work.rb +1 -1
- data/lib/rails_ai_admin.rb +10 -6
- data/lib/tasks/rails_ai_admin.rake +20 -0
- metadata +25 -2
|
@@ -5,7 +5,16 @@ module RailsAiAdmin
|
|
|
5
5
|
class ApplicationController < ActionController::Base
|
|
6
6
|
# Routing metadata is useful; arbitrary inputs and search text are not logs.
|
|
7
7
|
LOG_FILTER = /\A(?!(?:controller|action|resource|id|format)\z)/
|
|
8
|
-
|
|
8
|
+
# Rails 8.2 verifies requests by Sec-Fetch-Site, and its :header_only
|
|
9
|
+
# default accepts a request without that header over plain HTTP
|
|
10
|
+
# (rails/rails#56580; #58989 proposes an Origin check). The admin keeps a
|
|
11
|
+
# token check for such requests whatever the host's default: same-site
|
|
12
|
+
# headers pass, cross-site is refused, a missing header needs the token.
|
|
13
|
+
if ActionController::Base.respond_to?(:forgery_protection_verification_strategy)
|
|
14
|
+
protect_from_forgery with: :exception, using: :header_or_legacy_token
|
|
15
|
+
else
|
|
16
|
+
protect_from_forgery with: :exception
|
|
17
|
+
end
|
|
9
18
|
wrap_parameters false
|
|
10
19
|
layout "rails_ai_admin/application"
|
|
11
20
|
helper RailsAiAdmin::FieldsHelper
|
|
@@ -63,7 +72,7 @@ module RailsAiAdmin
|
|
|
63
72
|
private
|
|
64
73
|
|
|
65
74
|
def process_action(*)
|
|
66
|
-
filters = Array(request.get_header("action_dispatch.parameter_filter")) + [ LOG_FILTER ]
|
|
75
|
+
filters = Array(request.get_header("action_dispatch.parameter_filter")) + [ LOG_FILTER, RequestLogFilter::HEADER_FILTER ]
|
|
67
76
|
request.set_header("action_dispatch.parameter_filter", filters)
|
|
68
77
|
super
|
|
69
78
|
end
|
|
@@ -112,14 +121,14 @@ module RailsAiAdmin
|
|
|
112
121
|
end
|
|
113
122
|
end
|
|
114
123
|
|
|
115
|
-
def resolve_list_navigation
|
|
124
|
+
def resolve_list_navigation(strict: false)
|
|
116
125
|
raw = params[:return_to]
|
|
117
126
|
raw = raw.to_unsafe_h if raw.is_a?(ActionController::Parameters)
|
|
118
127
|
access = Authorization::Access.new(@context, @resource)
|
|
119
128
|
@list_navigation = if action_name == "recover_form"
|
|
120
129
|
Navigation::ListState.from_header(access, request.headers["X-RailsAiAdmin-Return-State"])
|
|
121
130
|
else
|
|
122
|
-
Navigation::ListState.new(access, raw)
|
|
131
|
+
Navigation::ListState.new(access, raw, strict: strict)
|
|
123
132
|
end
|
|
124
133
|
end
|
|
125
134
|
|
|
@@ -289,8 +298,12 @@ module RailsAiAdmin
|
|
|
289
298
|
end
|
|
290
299
|
|
|
291
300
|
def default_actor_label(ref)
|
|
292
|
-
|
|
293
|
-
|
|
301
|
+
text = ref.to_s
|
|
302
|
+
if (match = text.match(/\Araa:[^:]+:(.+):([^:]+)\z/))
|
|
303
|
+
"#{match[1].demodulize.titleize} ##{match[2]}"
|
|
304
|
+
else
|
|
305
|
+
text
|
|
306
|
+
end
|
|
294
307
|
end
|
|
295
308
|
|
|
296
309
|
def record_label(resource, record, values: nil, view: :show)
|
|
@@ -5,7 +5,7 @@ module RailsAiAdmin
|
|
|
5
5
|
# enqueues work; no provider call runs in a web request. RubyLLM is loaded
|
|
6
6
|
# inside actions only, so conventional hosts can eager-load this file.
|
|
7
7
|
class AssistantController < ApplicationController
|
|
8
|
-
RETRYABLE = %w[PROVIDER_UNAVAILABLE ASSISTANT_FAILED ATTEMPTS_EXHAUSTED AI_UNAVAILABLE
|
|
8
|
+
RETRYABLE = %w[PROVIDER_UNAVAILABLE ASSISTANT_FAILED ATTEMPTS_EXHAUSTED AI_UNAVAILABLE].freeze
|
|
9
9
|
FAILURES = {
|
|
10
10
|
"AI_UNAVAILABLE" => "The assistant is not available right now. The rest of the administration works as usual.",
|
|
11
11
|
"AI_REJECTED" => "The AI provider rejected this request. Try a shorter or different message.",
|
|
@@ -31,7 +31,7 @@ module RailsAiAdmin
|
|
|
31
31
|
# server-written "Context:" line naming that page.
|
|
32
32
|
def create
|
|
33
33
|
question = params[:content]
|
|
34
|
-
raise AccessDenied, "INVALID_QUERY" unless question.nil? || question.is_a?(String)
|
|
34
|
+
raise AccessDenied, "INVALID_QUERY" unless question.nil? || question.is_a?(String) && question.valid_encoding?
|
|
35
35
|
@chat = Assistant.create_chat!(@context)
|
|
36
36
|
if question.present?
|
|
37
37
|
content = [ page_context_line, question.strip ].compact.join("\n\n").first(Assistant::Coordinator::MAX_CONTENT)
|
|
@@ -60,7 +60,9 @@ module RailsAiAdmin
|
|
|
60
60
|
|
|
61
61
|
def message
|
|
62
62
|
return admin_status(:conflict) unless @chat.current_for?(@context)
|
|
63
|
-
|
|
63
|
+
key = params[:admission_key]
|
|
64
|
+
raise AccessDenied, "INVALID_QUERY" unless key.is_a?(String) && key.start_with?("message:")
|
|
65
|
+
Assistant::Coordinator.admit!(@chat, kind: "message", content: params[:content], admission_key: key)
|
|
64
66
|
redirect_to assistant_conversation_path(chat_ref: @chat.ref), status: :see_other
|
|
65
67
|
rescue AccessDenied => error
|
|
66
68
|
raise unless error.code == "INVALID_QUERY" || REFUSALS.include?(error.code)
|
|
@@ -83,17 +85,28 @@ module RailsAiAdmin
|
|
|
83
85
|
def retry_turn
|
|
84
86
|
return admin_status(:conflict) unless @chat.current_for?(@context)
|
|
85
87
|
Assistant::Turn.transaction do
|
|
86
|
-
Assistant::Chat.
|
|
87
|
-
|
|
88
|
+
Assistant::Chat.for_owner(@context).order(:id).lock.pluck(:id)
|
|
89
|
+
locked = Assistant::Chat.lock.find(@chat.id)
|
|
90
|
+
turn = locked.turns.reorder(sequence: :desc).first
|
|
88
91
|
raise AccessDenied, "CONFLICT" unless turn&.status == "failed" && RETRYABLE.include?(turn.error_code)
|
|
92
|
+
raise AccessDenied, "RATE_LIMITED" if Assistant::Coordinator.over_daily_limit?(locked)
|
|
93
|
+
raise AccessDenied, "BUDGET_EXCEEDED" if Assistant::Budget.exceeded?(locked)
|
|
89
94
|
turn.update!(status: "queued", attempts: 0, error_code: nil, next_attempt_at: nil, completed_at: nil)
|
|
90
95
|
end
|
|
91
96
|
Assistant::Coordinator.enqueue_after_commit(@chat.ref)
|
|
92
97
|
redirect_to assistant_conversation_path(chat_ref: @chat.ref), status: :see_other
|
|
98
|
+
rescue AccessDenied => error
|
|
99
|
+
raise unless REFUSALS.include?(error.code)
|
|
100
|
+
refuse_message(error.code, "")
|
|
93
101
|
end
|
|
94
102
|
|
|
95
103
|
def archive
|
|
96
|
-
|
|
104
|
+
Assistant::Turn.transaction do
|
|
105
|
+
locked = Assistant::Chat.lock.find(@chat.id)
|
|
106
|
+
locked.update!(status: "archived")
|
|
107
|
+
locked.turns.where(status: "queued").update_all(status: "cancelled", error_code: "CHAT_CLOSED", completed_at: Time.current, updated_at: Time.current)
|
|
108
|
+
locked.cancel if locked.turns.where(status: "running").exists?
|
|
109
|
+
end
|
|
97
110
|
redirect_to assistant_path, status: :see_other, notice: t("rails_ai_admin.assistant.archived")
|
|
98
111
|
end
|
|
99
112
|
|
|
@@ -133,7 +146,7 @@ module RailsAiAdmin
|
|
|
133
146
|
record = access.find!(id)
|
|
134
147
|
"Context: I am looking at #{resource.label.singularize} #{record.id} (\"#{access.record_label(record).truncate(120)}\") in the #{resource.key} resource."
|
|
135
148
|
else
|
|
136
|
-
query = about[:q].is_a?(String) ? about[:q].strip.first(100) : nil
|
|
149
|
+
query = about[:q].is_a?(String) && about[:q].valid_encoding? ? about[:q].strip.first(100) : nil
|
|
137
150
|
scope = about[:scope].is_a?(String) ? access.named_scopes.find { |definition| definition.name.to_s == about[:scope] } : nil
|
|
138
151
|
details = [ (query.present? ? "searching for \"#{query}\"" : nil), (scope ? "on the #{scope.label} tab (scope #{scope.name})" : nil) ].compact
|
|
139
152
|
"Context: I am looking at the #{resource.label} list (the #{resource.key} resource)#{details.any? ? ", #{details.join(', ')}" : ''}."
|
|
@@ -10,7 +10,11 @@ module RailsAiAdmin
|
|
|
10
10
|
@filters = FILTERS.to_h { |key| [ key, params[key] ] }.compact_blank
|
|
11
11
|
raise AccessDenied, "INVALID_QUERY" unless @filters.values.all? { |value| value.is_a?(String) }
|
|
12
12
|
@page = @log.page(**@filters.transform_keys(&:to_sym))
|
|
13
|
-
|
|
13
|
+
refs = @page.entries.map(&:actor_ref).uniq
|
|
14
|
+
actor = @filters["actor"]
|
|
15
|
+
refs << actor if actor && !refs.include?(actor) && @log.actor_present?(actor)
|
|
16
|
+
@actor_labels = actor_labels(refs)
|
|
17
|
+
@actor_labels[actor] ||= default_actor_label(actor) if actor
|
|
14
18
|
end
|
|
15
19
|
end
|
|
16
20
|
end
|
|
@@ -16,16 +16,16 @@ module RailsAiAdmin
|
|
|
16
16
|
def create
|
|
17
17
|
decision = params[:decision]
|
|
18
18
|
raise AccessDenied, "INVALID_QUERY" unless Operations::BulkChange::DECISIONS.include?(decision)
|
|
19
|
-
load_plan
|
|
20
|
-
if decision == "confirm"
|
|
21
|
-
Operations::BulkChange.verify_review!(params[:review_signature], params[:change], @ready)
|
|
22
|
-
raise AccessDenied if @ready.empty?
|
|
23
|
-
end
|
|
24
|
-
Operations::BulkChange.decide!(@selection, decision)
|
|
25
19
|
if decision == "dismiss"
|
|
20
|
+
load_dismiss_target
|
|
21
|
+
Operations::BulkChange.decide!(@selection, decision)
|
|
26
22
|
continue_chat("dismissed", "Nothing was changed.")
|
|
27
23
|
return redirect_to(return_path, status: :see_other, notice: t("rails_ai_admin.bulk_changes.dismissed"))
|
|
28
24
|
end
|
|
25
|
+
load_plan
|
|
26
|
+
Operations::BulkChange.verify_review!(params[:review_signature], params[:change], @ready)
|
|
27
|
+
raise AccessDenied if @ready.empty?
|
|
28
|
+
Operations::BulkChange.decide!(@selection, decision)
|
|
29
29
|
runner = Operations::Runner.new
|
|
30
30
|
outcomes = @ready.map do |item|
|
|
31
31
|
code = begin
|
|
@@ -68,6 +68,26 @@ module RailsAiAdmin
|
|
|
68
68
|
raise AccessDenied
|
|
69
69
|
end
|
|
70
70
|
|
|
71
|
+
# Dismissing never mutates domain records, so it stays allowed even if a
|
|
72
|
+
# selected record changed version after the proposal was created.
|
|
73
|
+
def load_dismiss_target
|
|
74
|
+
@proposal = Operations::BulkChange.decode(params[:change], context: @context)
|
|
75
|
+
raise AccessDenied unless @proposal.selection_ref == params[:selection_ref]
|
|
76
|
+
row = Selection.find_by(id: @proposal.selection_ref, actor_ref: @context.actor_ref,
|
|
77
|
+
tenant_ref: @context.tenant_ref, security_version: @context.security_version)
|
|
78
|
+
raise AccessDenied unless row && row.id == @proposal.selection_ref && row.expires_at && row.expires_at > Time.current &&
|
|
79
|
+
row.manifest_digest == @proposal.manifest_digest && row.resource_key == @proposal.resource_key
|
|
80
|
+
@resource = RailsAiAdmin.registry.fetch(row.resource_key)
|
|
81
|
+
raise AccessDenied unless @resource.assistant_change?(:bulk_update)
|
|
82
|
+
@selection = Selections::Builder::Snapshot.new(row.id, row.resource_key, row.manifest_digest, row.expires_at, [].freeze)
|
|
83
|
+
Operations::BulkChange.ensure_open!(@selection)
|
|
84
|
+
@ready = Array.new(row.item_count)
|
|
85
|
+
@fields = @resource.fields.select { |field| @proposal.values.key?(field.name.to_s) }
|
|
86
|
+
@chat_ref = @proposal.context_ref&.then { |value| value[/\Araa:chat:([0-9a-f-]{36})\z/, 1] }
|
|
87
|
+
rescue KeyError
|
|
88
|
+
raise AccessDenied
|
|
89
|
+
end
|
|
90
|
+
|
|
71
91
|
def return_path
|
|
72
92
|
@chat_ref ? assistant_conversation_path(chat_ref: @chat_ref) : resources_path(resource: @resource.key)
|
|
73
93
|
end
|
|
@@ -5,8 +5,9 @@ module RailsAiAdmin
|
|
|
5
5
|
# Counts appear only for resources whose list already opts into exact
|
|
6
6
|
# counts, with the same bound (10,000) and default list tab.
|
|
7
7
|
def index
|
|
8
|
-
|
|
9
|
-
@
|
|
8
|
+
visible = RailsAiAdmin.registry.resources.reject { |resource| resource.navigation.hidden }
|
|
9
|
+
@widgets = Presentation::Dashboard.build(@context, visible)
|
|
10
|
+
@counts = visible.each_with_object({}) do |resource, counts|
|
|
10
11
|
next unless resource.index.count == :exact
|
|
11
12
|
counts[resource.key.to_s] = Queries::List.new(@context, resource).count
|
|
12
13
|
rescue AccessDenied
|
|
@@ -14,18 +14,26 @@ module RailsAiAdmin
|
|
|
14
14
|
@page = page.to_i
|
|
15
15
|
records = @access.discarded_relation.offset((@page - 1) * PAGE_SIZE).limit(PAGE_SIZE + 1).to_a
|
|
16
16
|
@has_next = records.size > PAGE_SIZE
|
|
17
|
-
@records = records.first(PAGE_SIZE).
|
|
17
|
+
@records = records.first(PAGE_SIZE).filter_map do |record|
|
|
18
|
+
restorable = allowed_action?(@resource, :restore, record)
|
|
19
|
+
next unless restorable || allowed_action?(@resource, :show, record)
|
|
18
20
|
{ id: record.id.to_s, label: record_label(@resource, record), deleted_at: record.public_send(@resource.soft_delete),
|
|
19
|
-
version: RecordVersion.of(record).to_s, restorable:
|
|
21
|
+
version: RecordVersion.of(record).to_s, restorable: restorable }
|
|
20
22
|
end
|
|
21
23
|
end
|
|
22
24
|
|
|
23
25
|
def restore
|
|
24
26
|
Operations::Restore.new.call(context: @context, resource: @resource, id: params[:id], expected_version: params[:expected_version])
|
|
25
|
-
|
|
27
|
+
target = begin
|
|
28
|
+
@access.find!(params[:id])
|
|
29
|
+
resource_path(resource: @resource.key, id: params[:id], **navigation_params)
|
|
30
|
+
rescue AccessDenied
|
|
31
|
+
list_return_path
|
|
32
|
+
end
|
|
33
|
+
redirect_to target, status: :see_other, notice: t("rails_ai_admin.deleted_records.restored")
|
|
26
34
|
rescue AccessDenied => error
|
|
27
35
|
raise unless error.code == "CONFLICT"
|
|
28
|
-
redirect_to deleted_records_path(resource: @resource.key), status: :see_other, notice: t("rails_ai_admin.deleted_records.conflict")
|
|
36
|
+
redirect_to deleted_records_path(resource: @resource.key, **navigation_params), status: :see_other, notice: t("rails_ai_admin.deleted_records.conflict")
|
|
29
37
|
end
|
|
30
38
|
|
|
31
39
|
private
|
|
@@ -11,20 +11,21 @@ module RailsAiAdmin
|
|
|
11
11
|
access = Authorization::Access.new(@context, resource)
|
|
12
12
|
raise AccessDenied unless access.canonical_id?(params[:id])
|
|
13
13
|
record = access.find!(params[:id])
|
|
14
|
-
|
|
14
|
+
visible = access.fields(:read, record, view: :show) | access.fields(:read, record, view: :index)
|
|
15
|
+
field = visible.find { |candidate| Field::FILE_TYPES.include?(candidate.scalar_type) && candidate.name.to_s == params[:field] }
|
|
15
16
|
raise AccessDenied unless field
|
|
16
17
|
attached = access.attachment(record, field)
|
|
17
18
|
blob = if field.scalar_type == :files
|
|
18
19
|
id = params[:attachment]
|
|
19
|
-
raise AccessDenied unless
|
|
20
|
+
raise AccessDenied unless canonical_attachment_id?(id)
|
|
20
21
|
access.stored_attachments(record, field).find_by(id: id)&.blob
|
|
21
22
|
else
|
|
22
23
|
attached.attached? ? attached.blob : nil
|
|
23
24
|
end
|
|
24
|
-
raise AccessDenied unless blob
|
|
25
|
+
raise AccessDenied unless blob && blob.service.exist?(blob.key)
|
|
25
26
|
inline = params[:disposition] == "inline" && Fields::INLINE_IMAGE_TYPES.include?(blob.content_type)
|
|
26
27
|
# A served file is a document of its own: no script, no framing.
|
|
27
|
-
response.headers["Content-Security-Policy"] = "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox"
|
|
28
|
+
response.headers["Content-Security-Policy"] = "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'; sandbox"
|
|
28
29
|
response.headers["Cache-Control"] = "no-store, private"
|
|
29
30
|
response.headers["Content-Type"] = inline ? blob.content_type : "application/octet-stream"
|
|
30
31
|
response.headers["Content-Disposition"] = ActionDispatch::Http::ContentDisposition.format(
|
|
@@ -33,5 +34,16 @@ module RailsAiAdmin
|
|
|
33
34
|
# Streamed in the service's chunks; a large file is never held in memory.
|
|
34
35
|
self.response_body = Enumerator.new { |body| blob.download { |chunk| body << chunk } }
|
|
35
36
|
end
|
|
37
|
+
|
|
38
|
+
private
|
|
39
|
+
|
|
40
|
+
def canonical_attachment_id?(id)
|
|
41
|
+
return false unless id.is_a?(String) && id.valid_encoding? && id.bytesize.between?(1, 150) && !id.match?(/[[:cntrl:]]|[[:space:]]/)
|
|
42
|
+
case ::ActiveStorage::Attachment.type_for_attribute(::ActiveStorage::Attachment.primary_key).type
|
|
43
|
+
when :integer then id.match?(/\A[1-9][0-9]{0,18}\z/) && Integer(id, 10) <= 2**63 - 1
|
|
44
|
+
when :uuid then id.match?(/\A[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}\z/)
|
|
45
|
+
else id.match?(Field::REFERENCE)
|
|
46
|
+
end
|
|
47
|
+
end
|
|
36
48
|
end
|
|
37
49
|
end
|
|
@@ -11,8 +11,9 @@ module RailsAiAdmin
|
|
|
11
11
|
context, token = authenticate
|
|
12
12
|
return unauthorized unless context
|
|
13
13
|
require "rails_ai_admin/mcp"
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
return render(json: rpc_error(nil, -32600, "Request too large"), status: :content_too_large) if request.content_length.to_i > Mcp::MAX_BODY
|
|
15
|
+
raw = read_bounded_body
|
|
16
|
+
return render(json: rpc_error(nil, -32600, "Request too large"), status: :content_too_large) if raw.nil?
|
|
16
17
|
message = begin
|
|
17
18
|
JSON.parse(raw)
|
|
18
19
|
rescue JSON::ParserError
|
|
@@ -28,6 +29,9 @@ module RailsAiAdmin
|
|
|
28
29
|
server.handle(message)
|
|
29
30
|
end
|
|
30
31
|
body ? render(json: body, status: status) : head(status)
|
|
32
|
+
rescue StandardError => error
|
|
33
|
+
Rails.error.report(error, handled: true, severity: :error, source: "rails_ai_admin")
|
|
34
|
+
render json: rpc_error(message.is_a?(Hash) ? message["id"] : nil, -32603, "Internal error"), status: :internal_server_error
|
|
31
35
|
end
|
|
32
36
|
|
|
33
37
|
# No server-initiated stream and no session to end.
|
|
@@ -35,6 +39,25 @@ module RailsAiAdmin
|
|
|
35
39
|
|
|
36
40
|
private
|
|
37
41
|
|
|
42
|
+
# Prevent ActionController::Instrumentation from buffering and JSON-parsing
|
|
43
|
+
# untrusted bodies before auth/MAX_BODY checks, and keep MCP logs filtered
|
|
44
|
+
# even when mounted under a custom helper name.
|
|
45
|
+
def process_action(*)
|
|
46
|
+
filters = Array(request.get_header("action_dispatch.parameter_filter")) + [ ApplicationController::LOG_FILTER, RequestLogFilter::HEADER_FILTER ]
|
|
47
|
+
request.set_header("action_dispatch.parameter_filter", filters)
|
|
48
|
+
request.request_parameters = {}
|
|
49
|
+
super
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def read_bounded_body
|
|
53
|
+
body = request.body
|
|
54
|
+
return "" unless body
|
|
55
|
+
body.rewind if body.respond_to?(:rewind)
|
|
56
|
+
chunk = body.read(Mcp::MAX_BODY + 1).to_s
|
|
57
|
+
return nil if chunk.bytesize > Mcp::MAX_BODY
|
|
58
|
+
chunk
|
|
59
|
+
end
|
|
60
|
+
|
|
38
61
|
def prepare_headers
|
|
39
62
|
response.headers["Cache-Control"] = "no-store"
|
|
40
63
|
response.headers["X-Content-Type-Options"] = "nosniff"
|
|
@@ -44,7 +67,10 @@ module RailsAiAdmin
|
|
|
44
67
|
def same_origin?
|
|
45
68
|
origin = request.headers["Origin"]
|
|
46
69
|
return true if origin.blank?
|
|
47
|
-
URI.parse(origin)
|
|
70
|
+
uri = URI.parse(origin)
|
|
71
|
+
%w[http https].include?(uri.scheme) && uri.scheme == request.scheme &&
|
|
72
|
+
uri.host.is_a?(String) && uri.host.casecmp?(request.host) &&
|
|
73
|
+
uri.port == request.port && uri.userinfo.nil? && uri.path.empty? && uri.query.nil? && uri.fragment.nil?
|
|
48
74
|
rescue URI::InvalidURIError
|
|
49
75
|
false
|
|
50
76
|
end
|
|
@@ -63,7 +89,7 @@ module RailsAiAdmin
|
|
|
63
89
|
adapter.resolve_job(actor_ref: token.actor_ref, tenant_ref: token.tenant_ref, security_version: token.security_version)
|
|
64
90
|
end
|
|
65
91
|
unless context.is_a?(Context) && context.actor_ref == token.actor_ref && context.tenant_ref == token.tenant_ref &&
|
|
66
|
-
context.security_version == token.security_version
|
|
92
|
+
context.security_version == token.security_version && Assistant.available?(context)
|
|
67
93
|
return [ nil, nil ]
|
|
68
94
|
end
|
|
69
95
|
token.update_columns(last_used_at: Time.current) if token.last_used_at.nil? || token.last_used_at < 1.minute.ago
|
|
@@ -22,8 +22,10 @@ module RailsAiAdmin
|
|
|
22
22
|
end
|
|
23
23
|
|
|
24
24
|
def revoke
|
|
25
|
-
|
|
26
|
-
raise AccessDenied unless
|
|
25
|
+
id = params[:id]
|
|
26
|
+
raise AccessDenied unless id.is_a?(String) && id.match?(/\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/)
|
|
27
|
+
token = Mcp::AccessToken.for_owner(@context).find_by(id: id)
|
|
28
|
+
raise AccessDenied unless token && token.id == id && token.actor_ref == @context.actor_ref && token.tenant_ref == @context.tenant_ref
|
|
27
29
|
token.update!(revoked_at: Time.current) if token.revoked_at.nil?
|
|
28
30
|
redirect_to mcp_tokens_path, status: :see_other, notice: t("rails_ai_admin.mcp.revoked")
|
|
29
31
|
end
|
|
@@ -19,9 +19,12 @@ module RailsAiAdmin
|
|
|
19
19
|
if proposal.is_a?(Operations::Result)
|
|
20
20
|
render_failure(proposal, input)
|
|
21
21
|
else
|
|
22
|
+
@wire_input = JSON.generate(proposal.values.transform_values { |value| wire_value(value) })
|
|
23
|
+
if @wire_input.bytesize > 16_384
|
|
24
|
+
return render_failure(Operations::Result.new(code: "VALIDATION_FAILED", errors: { "base" => [ Field.error_message(:too_long, "is too long") ] }), input)
|
|
25
|
+
end
|
|
22
26
|
@proposal = proposal
|
|
23
27
|
@form_values = proposal.values
|
|
24
|
-
@wire_input = JSON.generate(proposal.values.transform_values { |value| wire_value(value) })
|
|
25
28
|
if request.format.turbo_stream?
|
|
26
29
|
render turbo_stream: turbo_stream.replace(@flow_id, template: "rails_ai_admin/operations/confirmation", layout: false)
|
|
27
30
|
else
|
|
@@ -84,7 +87,7 @@ module RailsAiAdmin
|
|
|
84
87
|
def wire_value(value)
|
|
85
88
|
case value
|
|
86
89
|
when BigDecimal then value.to_s("F")
|
|
87
|
-
when Time, ActiveSupport::TimeWithZone then value.
|
|
90
|
+
when Time, ActiveSupport::TimeWithZone then value.to_time.getutc.iso8601(6)
|
|
88
91
|
when Date then value.iso8601
|
|
89
92
|
else value
|
|
90
93
|
end
|
|
@@ -32,13 +32,19 @@ module RailsAiAdmin
|
|
|
32
32
|
@current_scope = @page.scope
|
|
33
33
|
@columns = @resource.index.order(@access.fields(:read, view: :index))
|
|
34
34
|
computed = @columns.map(&:name) | [ @resource.title ]
|
|
35
|
+
preload_index_associations(@page.records, @columns)
|
|
35
36
|
# A record inside the policy scope whose own show check fails is left out
|
|
36
37
|
# of the page, like an unavailable reference, instead of failing the
|
|
37
38
|
# whole list (RAA-001). The notice says rows were left out, never which.
|
|
38
39
|
@rows = @page.records.filter_map do |record|
|
|
39
40
|
values = @access.project(record, view: :index, only: computed)
|
|
40
|
-
|
|
41
|
-
|
|
41
|
+
editable = begin
|
|
42
|
+
@access.authorize!(:update, record)
|
|
43
|
+
rescue AccessDenied
|
|
44
|
+
false
|
|
45
|
+
end
|
|
46
|
+
{ id: record.id, label: @access.record_label(record, values: values, view: :index), values: values,
|
|
47
|
+
editable: editable }
|
|
42
48
|
rescue AccessDenied
|
|
43
49
|
@omitted_rows = true
|
|
44
50
|
nil
|
|
@@ -47,6 +53,10 @@ module RailsAiAdmin
|
|
|
47
53
|
@columns.select { |field| field.scalar_type == :belongs_to }.each do |field|
|
|
48
54
|
admin_associations.prime(field, @rows.filter_map { |row| row[:values][field.name.to_s] })
|
|
49
55
|
end
|
|
56
|
+
@columns.select { |field| field.scalar_type == :references }.each do |field|
|
|
57
|
+
ids = @rows.flat_map { |row| Array(row[:values][field.name.to_s]).first(FieldsHelper::REFERENCES_SHOWN) }.uniq
|
|
58
|
+
ids.each_slice(Fields::Association::MAX_BATCH) { |slice| admin_associations.prime(field, slice) }
|
|
59
|
+
end
|
|
50
60
|
@searchable = @access.fields(:search).any?
|
|
51
61
|
@omitted_rows ||= false
|
|
52
62
|
@selectable = begin
|
|
@@ -180,6 +190,7 @@ module RailsAiAdmin
|
|
|
180
190
|
input = operation == :destroy ? {} : submitted_input
|
|
181
191
|
@intent_ref = params[:intent_ref]
|
|
182
192
|
intent_id = runner.materialize_form_intent(context: @context, reference: @intent_ref)
|
|
193
|
+
raise AccessDenied unless intent_id
|
|
183
194
|
upload_files(operation, input) unless operation == :destroy
|
|
184
195
|
result = runner.execute(context: @context, intent_ref: intent_id, input: input,
|
|
185
196
|
human_confirmed: true, origin: :ui,
|
|
@@ -216,6 +227,7 @@ module RailsAiAdmin
|
|
|
216
227
|
def upload_files(operation, input)
|
|
217
228
|
@uploaded_blobs = []
|
|
218
229
|
record = operation == :create ? @access.relation.new : @access.find!(params[:id], action: operation)
|
|
230
|
+
@access.authorize!(operation, record)
|
|
219
231
|
writable = @access.fields(:write, record, operation: operation)
|
|
220
232
|
upload_lists(writable.select { |field| field.scalar_type == :files }, input)
|
|
221
233
|
files = writable.select { |field| field.scalar_type == :file }.index_by { |field| field.name.to_s }
|
|
@@ -263,6 +275,10 @@ module RailsAiAdmin
|
|
|
263
275
|
raise AccessDenied, "INVALID_QUERY" unless uploads.is_a?(Array) && remove.is_a?(Array) && remove.all? { |id| id.is_a?(String) }
|
|
264
276
|
uploads = uploads.reject { |value| value == "" }
|
|
265
277
|
raise AccessDenied, "INVALID_QUERY" unless uploads.all? { |value| value.is_a?(ActionDispatch::Http::UploadedFile) }
|
|
278
|
+
if uploads.size > field.options[:max_files]
|
|
279
|
+
input[name] = { "add" => Array.new(uploads.size, Fields::RejectedUpload.new("too_many", field.options[:max_files])), "remove" => remove }
|
|
280
|
+
next
|
|
281
|
+
end
|
|
266
282
|
added = uploads.map { |value| value.size > field.options[:max_size] ? Fields::RejectedUpload.new("too_large", field.options[:max_size]) : store_upload(value) }
|
|
267
283
|
if added.empty? && remove.empty?
|
|
268
284
|
input.delete(name)
|
|
@@ -284,6 +300,19 @@ module RailsAiAdmin
|
|
|
284
300
|
value.is_a?(ActionController::Parameters) ? value.to_unsafe_h : {}
|
|
285
301
|
end
|
|
286
302
|
|
|
303
|
+
def preload_index_associations(records, fields)
|
|
304
|
+
return if records.empty?
|
|
305
|
+
model = @resource.model_class
|
|
306
|
+
associations = fields.filter_map do |field|
|
|
307
|
+
case field.scalar_type
|
|
308
|
+
when :file then { "#{field.column}_attachment": :blob } if model.reflect_on_association(:"#{field.column}_attachment")
|
|
309
|
+
when :rich_text then :"rich_text_#{field.column}" if model.reflect_on_association(:"rich_text_#{field.column}")
|
|
310
|
+
when :references then field.name if model.reflect_on_association(field.name)
|
|
311
|
+
end
|
|
312
|
+
end
|
|
313
|
+
ActiveRecord::Associations::Preloader.new(records: records, associations: associations).call if associations.any?
|
|
314
|
+
end
|
|
315
|
+
|
|
287
316
|
def build_form_plan(operation, input = nil)
|
|
288
317
|
view = operation == :create ? :create : :edit
|
|
289
318
|
@form_fields = @access.fields(:write, @record, operation: operation)
|
|
@@ -295,9 +324,19 @@ module RailsAiAdmin
|
|
|
295
324
|
names = @form_fields.map { |field| field.name.to_s }
|
|
296
325
|
@form_values = readable_values.slice(*names)
|
|
297
326
|
if input.is_a?(Hash)
|
|
298
|
-
#
|
|
299
|
-
|
|
300
|
-
@
|
|
327
|
+
# Refused files and passwords are never echoed back into form values.
|
|
328
|
+
excluded = @form_fields.select { |field| Field::FILE_TYPES.include?(field.scalar_type) || field.scalar_type == :password }.map { |field| field.name.to_s }
|
|
329
|
+
references = @form_fields.select { |field| field.scalar_type == :references }.map { |field| field.name.to_s }
|
|
330
|
+
input.stringify_keys.slice(*(names - excluded)).each do |name, value|
|
|
331
|
+
if references.include?(name)
|
|
332
|
+
next unless value.is_a?(Array) && value.size <= Field::MAX_REFERENCES + 1
|
|
333
|
+
keys = value.select { |item| item.is_a?(String) && item.valid_encoding? && item.present? }.uniq
|
|
334
|
+
@form_values[name] = keys
|
|
335
|
+
elsif !value.is_a?(Hash) && !value.is_a?(Array)
|
|
336
|
+
next if value.is_a?(String) && value.bytesize > Forms::Plan::MAX_VALUE_BYTES
|
|
337
|
+
@form_values[name] = value
|
|
338
|
+
end
|
|
339
|
+
end
|
|
301
340
|
end
|
|
302
341
|
readonly_fields = @access.fields(:read, @record, view: view).select { |field| readable_values.key?(field.name.to_s) && !names.include?(field.name.to_s) }
|
|
303
342
|
readonly_values = readable_values.slice(*readonly_fields.map { |field| field.name.to_s })
|
|
@@ -3,9 +3,16 @@
|
|
|
3
3
|
module RailsAiAdmin
|
|
4
4
|
# Snapshot capture/view is deliberately separate from business confirmation.
|
|
5
5
|
class SelectionsController < ApplicationController
|
|
6
|
+
DESTROY_REVIEW_PURPOSE = "rails_ai_admin/selection_destroy_review"
|
|
7
|
+
|
|
6
8
|
def create
|
|
7
9
|
@resource = RailsAiAdmin.registry.fetch(params[:resource])
|
|
8
|
-
|
|
10
|
+
if params[:all_matching] == "1"
|
|
11
|
+
resolve_list_navigation(strict: true)
|
|
12
|
+
raise AccessDenied, "INVALID_QUERY" if return_state_discarded?
|
|
13
|
+
else
|
|
14
|
+
resolve_list_navigation
|
|
15
|
+
end
|
|
9
16
|
target_ids = if params[:all_matching] == "1"
|
|
10
17
|
Authorization::Access.new(@context, @resource).authorize_selection!
|
|
11
18
|
ids = matching_ids
|
|
@@ -46,7 +53,10 @@ module RailsAiAdmin
|
|
|
46
53
|
# now, and how many will be skipped. With none, the selection stays.
|
|
47
54
|
def confirm_destroy
|
|
48
55
|
load_deletable
|
|
49
|
-
|
|
56
|
+
if @deletable.any?
|
|
57
|
+
@review_signature = sign_destroy_review(@selection, @deletable)
|
|
58
|
+
return
|
|
59
|
+
end
|
|
50
60
|
redirect_to selection_path(selection_ref: @selection.selection_ref, **navigation_params), status: :see_other,
|
|
51
61
|
notice: t("rails_ai_admin.selections.destroy.none")
|
|
52
62
|
end
|
|
@@ -58,6 +68,7 @@ module RailsAiAdmin
|
|
|
58
68
|
digest = params[:manifest_digest]
|
|
59
69
|
raise AccessDenied, "INVALID_QUERY" unless digest.is_a?(String) && digest.match?(/\A[0-9a-f]{64}\z/)
|
|
60
70
|
load_deletable(manifest_digest: digest)
|
|
71
|
+
verify_destroy_review!(params[:review_signature], @selection, @deletable)
|
|
61
72
|
raise AccessDenied if @deletable.empty?
|
|
62
73
|
runner = Operations::Runner.new
|
|
63
74
|
@outcomes = @deletable.map do |target|
|
|
@@ -86,11 +97,36 @@ module RailsAiAdmin
|
|
|
86
97
|
# The builder then checks each of them again.
|
|
87
98
|
def matching_ids
|
|
88
99
|
state = navigation_state
|
|
89
|
-
|
|
90
|
-
Queries::List.new(@context, @resource).relation(search: state["q"], sort: state["sort"], direction: state.fetch("direction", "asc"),
|
|
91
|
-
scope: state["scope"], filters: state["filter"]).limit(Selections::Builder::LIMIT + 1).
|
|
100
|
+
access = Authorization::Access.new(@context, @resource)
|
|
101
|
+
records = Queries::List.new(@context, @resource).relation(search: state["q"], sort: state["sort"], direction: state.fetch("direction", "asc"),
|
|
102
|
+
scope: state["scope"], filters: state["filter"]).limit(Selections::Builder::LIMIT + 1).to_a
|
|
103
|
+
records.filter_map do |record|
|
|
104
|
+
access.authorize!(:show, record)
|
|
105
|
+
record.id.to_s
|
|
106
|
+
rescue AccessDenied
|
|
107
|
+
nil
|
|
108
|
+
end
|
|
92
109
|
end
|
|
93
110
|
|
|
111
|
+
def sign_destroy_review(selection, targets)
|
|
112
|
+
destroy_review_verifier.generate(destroy_review_digest(selection, targets),
|
|
113
|
+
expires_at: selection.expires_at, purpose: DESTROY_REVIEW_PURPOSE)
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
def verify_destroy_review!(signature, selection, targets)
|
|
117
|
+
raise AccessDenied, "INVALID_QUERY" unless signature.is_a?(String) && signature.bytesize.between?(1, 1024)
|
|
118
|
+
unless destroy_review_verifier.verified(signature, purpose: DESTROY_REVIEW_PURPOSE) == destroy_review_digest(selection, targets)
|
|
119
|
+
raise AccessDenied, "CONFLICT"
|
|
120
|
+
end
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
def destroy_review_digest(selection, targets)
|
|
124
|
+
InputSchema.digest(selection_ref: selection.selection_ref, manifest_digest: selection.manifest_digest,
|
|
125
|
+
actor_ref: @context.actor_ref, tenant_ref: @context.tenant_ref, ids: targets.map(&:id))
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
def destroy_review_verifier = ::Rails.application.message_verifier(DESTROY_REVIEW_PURPOSE)
|
|
129
|
+
|
|
94
130
|
# The list's bulk buttons name the action to review next. An unknown or
|
|
95
131
|
# ungranted name falls back to the selection page; nothing runs here.
|
|
96
132
|
def next_step_path(selection_ref)
|
|
@@ -7,7 +7,9 @@ module RailsAiAdmin
|
|
|
7
7
|
def assistant_spend_text(spend)
|
|
8
8
|
parts = []
|
|
9
9
|
if spend.token_limit
|
|
10
|
-
|
|
10
|
+
tokens = t("rails_ai_admin.assistant.spend.tokens", used: number_with_delimiter(spend.tokens), limit: number_with_delimiter(spend.token_limit))
|
|
11
|
+
tokens = "#{tokens} #{t('rails_ai_admin.assistant.spend.cached', count: number_with_delimiter(spend.cached))}" if spend.cached.positive?
|
|
12
|
+
parts << tokens
|
|
11
13
|
end
|
|
12
14
|
if spend.cost_limit
|
|
13
15
|
parts << t("rails_ai_admin.assistant.spend.cost", used: assistant_dollars(spend.cost), limit: assistant_dollars(spend.cost_limit))
|