Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Restrict instance-wide settings to super admins (#3794)

GFR0049d64ec541
diff --git a/app/controllers/settings/hostings_controller.rb b/app/controllers/settings/hostings_controller.rb
index 6b16ae7540..2c407f2050 100644
--- a/app/controllers/settings/hostings_controller.rb
+++ b/app/controllers/settings/hostings_controller.rb
@@ -17,6 +17,7 @@ class Settings::HostingsController < ApplicationController
guard_feature unless: -> { self_hosted? }
before_action :ensure_admin, only: [ :update, :clear_cache, :disconnect_external_assistant ]
+ before_action :ensure_instance_settings_manager, only: [ :update, :disconnect_external_assistant ]
before_action :ensure_super_admin_for_onboarding, only: :update
def show
@@ -487,6 +488,13 @@ class Settings::HostingsController < ApplicationController
redirect_to settings_hosting_path, alert: t(".not_authorized") unless Current.user.admin?
end
+ # Everything under params[:setting] is stored in the global Setting and
+ # applies to every family; params[:family] only touches Current.family.
+ def ensure_instance_settings_manager
+ return unless action_name == "disconnect_external_assistant" || params.key?(:setting)
+ redirect_to settings_hosting_path, alert: t(".not_authorized") unless Current.user.manages_instance_settings?
+ end
+
def ensure_super_admin_for_onboarding
onboarding_params = %i[onboarding_state invite_only_default_family_id]
return unless onboarding_params.any? { |p| hosting_params.key?(p) }
diff --git a/app/controllers/settings/providers_controller.rb b/app/controllers/settings/providers_controller.rb
index c70225121b..2762b8e31b 100644
--- a/app/controllers/settings/providers_controller.rb
+++ b/app/controllers/settings/providers_controller.rb
@@ -2,6 +2,7 @@ class Settings::ProvidersController < ApplicationController
layout -> { turbo_frame_request? ? "turbo_rails/frame" : "settings" }
before_action :ensure_admin, only: [ :show, :update, :sync_all, :sync, :connect_form ]
+ before_action :ensure_instance_settings_manager, only: :update
before_action :set_encryption_warning_context, only: [ :show, :connect_form ]
def show
@@ -125,6 +126,10 @@ class Settings::ProvidersController < ApplicationController
Provider::Factory.ensure_adapters_loaded
config = Provider::ConfigurationRegistry.all.find { |c| c.provider_key.to_s == provider_key }
if config
+ unless Current.user.manages_instance_settings?
+ return redirect_to settings_providers_path, alert: t("settings.providers.not_authorized")
+ end
+
@panel_title = Provider::Metadata.for(provider_key)[:name] || provider_key.titleize
@provider_configuration = config
return render :connect_form
@@ -156,6 +161,14 @@ class Settings::ProvidersController < ApplicationController
redirect_to root_path, alert: t("settings.providers.not_authorized")
end
+ # Registry-driven configurations (e.g. Plaid) are stored in the global
+ # Setting and apply to every family on the instance.
+ def ensure_instance_settings_manager
+ return if Current.user.manages_instance_settings?
+
+ redirect_to settings_providers_path, alert: t("settings.providers.not_authorized")
+ end
+
def set_encryption_warning_context
@provider_setup_encryption_warning = Rails.configuration.app_mode.self_hosted? &&
!ActiveRecordEncryptionConfig.explicitly_configured?
@@ -302,11 +315,13 @@ class Settings::ProvidersController < ApplicationController
# Prepares instance vars needed by the show view and partials
def prepare_show_context
- # Load all provider configurations (exclude family-scoped panels, which have their own UI below)
+ # Load all provider configurations (exclude family-scoped panels, which have their own UI below).
+ # They edit instance-wide credentials, so only those who may change them see them.
Provider::Factory.ensure_adapters_loaded
@provider_configurations = Provider::ConfigurationRegistry.all.reject do |config|
FAMILY_PANEL_KEYS.any? { |key| config.provider_key.to_s.casecmp(key).zero? }
end
+ @provider_configurations = [] unless Current.user.manages_instance_settings?
@akahu_items = Current.family.akahu_items.active.ordered
@up_items = Current.family.up_items.active.ordered
diff --git a/app/models/user.rb b/app/models/user.rb
index 936c9f9914..cccf97f414 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -161,6 +161,17 @@ class User < ApplicationRecord
super_admin? || role == "admin"
end
+ # Setting values are shared by every family on the instance, so changing them
+ # is a super admin's job: a family admin is anyone who signed up. A
+ # self-hosted instance with a single family has no other tenant to protect,
+ # and installs that predate the super_admin role may not have one, so that
+ # family's admins keep access there.
+ def manages_instance_settings?
+ return true if super_admin?
+
+ admin? && Rails.application.config.app_mode.self_hosted? && Family.count == 1
+ end
+
def accessible_accounts
family.accounts.accessible_by(self)
end
diff --git a/app/views/settings/hostings/_assistant_settings.html.erb b/app/views/settings/hostings/_assistant_settings.html.erb
index 175500700a..2827c85ab8 100644
--- a/app/views/settings/hostings/_assistant_settings.html.erb
+++ b/app/views/settings/hostings/_assistant_settings.html.erb
@@ -60,69 +60,72 @@
<p class="text-sm text-secondary"><%= t(".env_configured_external") %></p>
<% end %>
- <% if Assistant::External.configured? && !ENV["EXTERNAL_ASSISTANT_URL"].present? %>
- <div class="flex items-center justify-between p-3 rounded-lg border border-primary">
- <div>
- <p class="text-sm font-medium text-primary"><%= t(".disconnect_title") %></p>
- <p class="text-xs text-secondary"><%= t(".disconnect_description") %></p>
+ <%# The endpoint and token are instance-wide Setting values. %>
+ <% if local_assigns[:manages_instance_settings] %>
+ <% if Assistant::External.configured? && !ENV["EXTERNAL_ASSISTANT_URL"].present? %>
+ <div class="flex items-center justify-between p-3 rounded-lg border border-primary">
+ <div>
+ <p class="text-sm font-medium text-primary"><%= t(".disconnect_title") %></p>
+ <p class="text-xs text-secondary"><%= t(".disconnect_description") %></p>
+ </div>
+ <%= button_to t(".disconnect_button"),
+ disconnect_external_assistant_settings_hosting_path,
+ method: :delete,
+ class: "bg-red-600 text-inverse text-sm font-medium rounded-lg px-4 py-2 whitespace-nowrap",
+ data: { turbo_confirm: {
+ title: t(".confirm_disconnect.title"),
+ body: t(".confirm_disconnect.body"),
+ accept: t(".disconnect_button"),
+ acceptClass: "w-full bg-red-600 text-inverse rounded-xl text-center p-[10px] border mb-2"
+ }} %>
</div>
- <%= button_to t(".disconnect_button"),
- disconnect_external_assistant_settings_hosting_path,
- method: :delete,
- class: "bg-red-600 text-inverse text-sm font-medium rounded-lg px-4 py-2 whitespace-nowrap",
- data: { turbo_confirm: {
- title: t(".confirm_disconnect.title"),
- body: t(".confirm_disconnect.body"),
- accept: t(".disconnect_button"),
- acceptClass: "w-full bg-red-600 text-inverse rounded-xl text-center p-[10px] border mb-2"
- }} %>
- </div>
- <% end %>
+ <% end %>
- <%= styled_form_with model: Setting.new,
- url: settings_hosting_path,
- method: :patch,
- class: "space-y-4",
- data: {
- controller: "auto-submit-form",
- "auto-submit-form-trigger-event-value": "blur"
- } do |form| %>
- <%= form.text_field :external_assistant_url,
- label: t(".url_label"),
- placeholder: t(".url_placeholder"),
- value: Assistant::External.config.url,
- autocomplete: "off",
- autocapitalize: "none",
- spellcheck: "false",
- inputmode: "url",
- disabled: ENV["EXTERNAL_ASSISTANT_URL"].present?,
- data: { "auto-submit-form-target": "auto" } %>
- <p class="text-xs text-secondary mt-1"><%= t(".url_help") %></p>
+ <%= styled_form_with model: Setting.new,
+ url: settings_hosting_path,
+ method: :patch,
+ class: "space-y-4",
+ data: {
+ controller: "auto-submit-form",
+ "auto-submit-form-trigger-event-value": "blur"
+ } do |form| %>
+ <%= form.text_field :external_assistant_url,
+ label: t(".url_label"),
+ placeholder: t(".url_placeholder"),
+ value: Assistant::External.config.url,
+ autocomplete: "off",
+ autocapitalize: "none",
+ spellcheck: "false",
+ inputmode: "url",
+ disabled: ENV["EXTERNAL_ASSISTANT_URL"].present?,
+ data: { "auto-submit-form-target": "auto" } %>
+ <p class="text-xs text-secondary mt-1"><%= t(".url_help") %></p>
- <%= form.password_field :external_assistant_token,
- label: t(".token_label"),
- placeholder: t(".token_placeholder"),
- value: (Assistant::External.config.token.present? ? "********" : nil),
- autocomplete: "off",
- autocapitalize: "none",
- spellcheck: "false",
- inputmode: "text",
- disabled: ENV["EXTERNAL_ASSISTANT_TOKEN"].present?,
- data: { "auto-submit-form-target": "auto" } %>
- <p class="text-xs text-secondary mt-1"><%= t(".token_help") %></p>
+ <%= form.password_field :external_assistant_token,
+ label: t(".token_label"),
+ placeholder: t(".token_placeholder"),
+ value: (Assistant::External.config.token.present? ? "********" : nil),
+ autocomplete: "off",
+ autocapitalize: "none",
+ spellcheck: "false",
+ inputmode: "text",
+ disabled: ENV["EXTERNAL_ASSISTANT_TOKEN"].present?,
+ data: { "auto-submit-form-target": "auto" } %>
+ <p class="text-xs text-secondary mt-1"><%= t(".token_help") %></p>
- <% model_options = Array(@external_assistant_models).map { |agent| [agent[:label], agent[:id]] } %>
- <% selected_model = Assistant::External.config.model %>
- <%= form.select :external_assistant_model,
- options_for_select(model_options, selected_model),
- { label: t(".agent_id_label"), include_blank: false },
- { aria: { required: true }, disabled: ENV["EXTERNAL_ASSISTANT_MODEL"].present? || model_options.empty?,
- data: { "auto-submit-form-target": "auto" } } %>
- <p class="text-xs text-secondary mt-1"><%= t(".agent_id_help") %></p>
- <% if @external_assistant_catalog_error.present? %>
- <p class="text-xs text-destructive mt-1"><%= t(".agent_discovery_error", error: @external_assistant_catalog_error) %></p>
- <% elsif !Assistant::External.configured? %>
- <p class="text-xs text-secondary mt-1"><%= t(".agent_discovery_configure_first") %></p>
+ <% model_options = Array(@external_assistant_models).map { |agent| [agent[:label], agent[:id]] } %>
+ <% selected_model = Assistant::External.config.model %>
+ <%= form.select :external_assistant_model,
+ options_for_select(model_options, selected_model),
+ { label: t(".agent_id_label"), include_blank: false },
+ { aria: { required: true }, disabled: ENV["EXTERNAL_ASSISTANT_MODEL"].present? || model_options.empty?,
+ data: { "auto-submit-form-target": "auto" } } %>
+ <p class="text-xs text-secondary mt-1"><%= t(".agent_id_help") %></p>
+ <% if @external_assistant_catalog_error.present? %>
+ <p class="text-xs text-destructive mt-1"><%= t(".agent_discovery_error", error: @external_assistant_catalog_error) %></p>
+ <% elsif !Assistant::External.configured? %>
+ <p class="text-xs text-secondary mt-1"><%= t(".agent_discovery_configure_first") %></p>
+ <% end %>
<% end %>
<% end %>
<% end %>
diff --git a/app/views/settings/hostings/_categorization_provider_selector.html.erb b/app/views/settings/hostings/_categorization_provider_selector.html.erb
index 11ac6afeb6..e12dc21eb7 100644
--- a/app/views/settings/hostings/_categorization_provider_selector.html.erb
+++ b/app/views/settings/hostings/_categorization_provider_selector.html.erb
@@ -59,7 +59,9 @@
<% end %>
</div>
- <%= render "settings/hostings/jev_settings" %>
+ <% if local_assigns[:manages_instance_settings] %>
+ <%= render "settings/hostings/jev_settings" %>
+ <% end %>
<%# Only meaningful for a provider that reports confidence — the LLM
providers return a bare category name, so there is nothing to threshold
diff --git a/app/views/settings/hostings/show.html.erb b/app/views/settings/hostings/show.html.erb
index 77013b39df..5def17e48b 100644
--- a/app/views/settings/hostings/show.html.erb
+++ b/app/views/settings/hostings/show.html.erb
@@ -1,71 +1,83 @@
<%= content_for :page_title, t(".title") %>
+<% manages_instance_settings = Current.user.manages_instance_settings? %>
+<% unless manages_instance_settings %>
+ <%= render DS::Alert.new(message: t(".instance_settings_restricted"), variant: :info) %>
+<% end %>
<%= settings_section title: t(".ai_assistant") do %>
- <%= render "settings/hostings/assistant_settings" %>
+ <%= render "settings/hostings/assistant_settings", manages_instance_settings: manages_instance_settings %>
<% end %>
-<%= settings_section title: t(".general") do %>
- <div class="space-y-6"
- data-controller="provider-settings"
- data-provider-settings-active-value="<%= Setting.llm_provider %>">
- <%= render "settings/hostings/llm_provider_selector" %>
- <%= tag.div data: { "provider-settings-target": "panel", provider: "openai" },
- hidden: Setting.llm_provider != "openai" do %>
- <%= render "settings/hostings/openai_settings" %>
- <% end %>
- <%= tag.div data: { "provider-settings-target": "panel", provider: "anthropic" },
- hidden: Setting.llm_provider != "anthropic" do %>
- <%= render "settings/hostings/anthropic_settings" %>
- <% end %>
- <%# Jev is a classification provider, not an LLM: it answers typed questions
- and cannot generate text. This sits outside the panels above so the
- llm_provider selector never shows or hides it — that selector governs
- chat and PDF, which Jev can never serve. The panel renders its own
- credential fields once Jev is selected.
+<% if manages_instance_settings || preview_features_enabled? %>
+ <%= settings_section title: t(".general") do %>
+ <div class="space-y-6"
+ data-controller="provider-settings"
+ data-provider-settings-active-value="<%= Setting.llm_provider %>">
+ <% if manages_instance_settings %>
+ <%= render "settings/hostings/llm_provider_selector" %>
+ <%= tag.div data: { "provider-settings-target": "panel", provider: "openai" },
+ hidden: Setting.llm_provider != "openai" do %>
+ <%= render "settings/hostings/openai_settings" %>
+ <% end %>
+ <%= tag.div data: { "provider-settings-target": "panel", provider: "anthropic" },
+ hidden: Setting.llm_provider != "anthropic" do %>
+ <%= render "settings/hostings/anthropic_settings" %>
+ <% end %>
+ <% end %>
+ <%# Jev is a classification provider, not an LLM: it answers typed questions
+ and cannot generate text. This sits outside the panels above so the
+ llm_provider selector never shows or hides it — that selector governs
+ chat and PDF, which Jev can never serve. The panel renders its own
+ credential fields once Jev is selected.
- Preview gates the entry point only — see
- docs/llm-guides/gating-a-preview-feature.md. Resolution reads the family
- column, so a family that opts in and then picks the LLM provider keeps
- the LLM provider. %>
- <% if preview_features_enabled? %>
- <%= render "settings/hostings/categorization_provider_selector" %>
- <% end %>
- <%= render "settings/hostings/brand_fetch_settings" %>
- </div>
-<% end %>
-<%= settings_section title: t(".financial_data_providers") do %>
- <div class="space-y-6">
- <%= render "settings/hostings/provider_selection" %>
- <% if @show_yahoo_finance_settings %>
- <%= render "settings/hostings/yahoo_finance_settings" %>
- <% end %>
- <% if @show_twelve_data_settings %>
- <%= render "settings/hostings/twelve_data_settings" %>
- <% end %>
- <% if @show_tiingo_settings %>
- <%= render "settings/hostings/tiingo_settings" %>
- <% end %>
- <% if @show_eodhd_settings %>
- <%= render "settings/hostings/eodhd_settings" %>
- <% end %>
- <% if @show_alpha_vantage_settings %>
- <%= render "settings/hostings/alpha_vantage_settings" %>
- <% end %>
- <% if @show_tinkoff_invest_settings %>
- <%= render "settings/hostings/tinkoff_invest_settings" %>
- <% end %>
- <% if @show_mansa_settings %>
- <%= render "settings/hostings/mansa_settings" %>
- <% end %>
- </div>
-<% end %>
-<%= settings_section title: t(".property_valuation_providers") do %>
- <div class="space-y-6">
- <%= render "settings/hostings/rentcast_settings" %>
- <%= render "settings/hostings/realie_settings" %>
- <%= render "settings/hostings/chimnie_settings" %>
- </div>
+ Preview gates the entry point only — see
+ docs/llm-guides/gating-a-preview-feature.md. Resolution reads the family
+ column, so a family that opts in and then picks the LLM provider keeps
+ the LLM provider. %>
+ <% if preview_features_enabled? %>
+ <%= render "settings/hostings/categorization_provider_selector", manages_instance_settings: manages_instance_settings %>
+ <% end %>
+ <% if manages_instance_settings %>
+ <%= render "settings/hostings/brand_fetch_settings" %>
+ <% end %>
+ </div>
+ <% end %>
<% end %>
-<%= settings_section title: t(".sync_settings") do %>
- <%= render "settings/hostings/sync_settings" %>
+<% if manages_instance_settings %>
+ <%= settings_section title: t(".financial_data_providers") do %>
+ <div class="space-y-6">
+ <%= render "settings/hostings/provider_selection" %>
+ <% if @show_yahoo_finance_settings %>
+ <%= render "settings/hostings/yahoo_finance_settings" %>
+ <% end %>
+ <% if @show_twelve_data_settings %>
+ <%= render "settings/hostings/twelve_data_settings" %>
+ <% end %>
+ <% if @show_tiingo_settings %>
+ <%= render "settings/hostings/tiingo_settings" %>
+ <% end %>
+ <% if @show_eodhd_settings %>
+ <%= render "settings/hostings/eodhd_settings" %>
+ <% end %>
+ <% if @show_alpha_vantage_settings %>
+ <%= render "settings/hostings/alpha_vantage_settings" %>
+ <% end %>
+ <% if @show_tinkoff_invest_settings %>
+ <%= render "settings/hostings/tinkoff_invest_settings" %>
+ <% end %>
+ <% if @show_mansa_settings %>
+ <%= render "settings/hostings/mansa_settings" %>
+ <% end %>
+ </div>
+ <% end %>
+ <%= settings_section title: t(".property_valuation_providers") do %>
+ <div class="space-y-6">
+ <%= render "settings/hostings/rentcast_settings" %>
+ <%= render "settings/hostings/realie_settings" %>
+ <%= render "settings/hostings/chimnie_settings" %>
+ </div>
+ <% end %>
+ <%= settings_section title: t(".sync_settings") do %>
+ <%= render "settings/hostings/sync_settings" %>
+ <% end %>
<% end %>
<% if Current.user.super_admin? %>
<%= settings_section title: t(".invites") do %>
diff --git a/config/locales/views/settings/hostings/de.yml b/config/locales/views/settings/hostings/de.yml
index a8ca4929a8..63a3bacbc6 100644
--- a/config/locales/views/settings/hostings/de.yml
+++ b/config/locales/views/settings/hostings/de.yml
@@ -23,6 +23,7 @@ de:
invites: Einladungscodes
title: Self-Hosting
danger_zone: Gefahrenbereich
+ instance_settings_restricted: Anbieter-Zugangsdaten, die gemeinsame KI-Verbindung und Synchronisierungseinstellungen gelten für alle Familien dieser Instanz und können daher nur von einem Super-Admin geändert werden. Welchen Assistenten deine Familie nutzt, wird weiterhin pro Familie festgelegt. Wer Zugriff auf den Server hat, kann einen Benutzer zum Super-Admin machen; den Befehl nennt die Docker-Self-Hosting-Anleitung in ihren Upgrade-Hinweisen.
clear_cache: Daten-Cache leeren
clear_cache_warning: Das Leeren des Daten-Caches entfernt alle Wechselkurse, Wertpapierpreise, Kontostände und andere zwischengespeicherte Daten. Dies löscht keine Konten, Transaktionen, Kategorien oder andere benutzereigenen Daten.
confirm_clear_cache:
diff --git a/config/locales/views/settings/hostings/en.yml b/config/locales/views/settings/hostings/en.yml
index 474cba33f2..381b6b32f0 100644
--- a/config/locales/views/settings/hostings/en.yml
+++ b/config/locales/views/settings/hostings/en.yml
@@ -33,6 +33,7 @@ en:
invites: Invite Codes
title: Self-Hosting
danger_zone: Danger Zone
+ instance_settings_restricted: Provider credentials, the shared AI connection and sync settings apply to every family on this instance, so only a super admin can change them. Which assistant your family uses is still set per family. Someone with access to the server can promote a user to super admin; the Docker self-hosting guide shows the command in its upgrade notes.
clear_cache: Clear data cache
clear_cache_warning: Clearing the data cache will remove all exchange rates, security prices, account balances, and other data. This will not delete accounts, transactions, categories, or other user-owned data.
confirm_clear_cache:
diff --git a/docs/hosting/docker.md b/docs/hosting/docker.md
index 5d3892332d..7e0a31614a 100644
--- a/docs/hosting/docker.md
+++ b/docs/hosting/docker.md
@@ -440,6 +440,18 @@ docker compose pull web worker # Pull the newest image for your tag
docker compose up -d # Restart on the new version; database migrations run automatically
```
+### Upgrade note: instance-wide settings need a super admin
+
+Provider credentials (such as Plaid), the shared AI connection settings (LLM provider, endpoints, API keys and models), sync settings, and the external assistant connection are stored once for the whole instance and apply to every family. On an instance with more than one family, only a `super_admin` can change them. When there is a single family, its admins keep access. Family-scoped choices, such as which assistant a family uses, stay with that family's admins.
+
+Installs created before the first user was automatically made `super_admin` may have no super admin at all. If your instance has more than one family (for example, because someone else signed up), these instance-wide settings are hidden after the update and saving them returns "not authorized". Promote your own user once:
+
+```bash
+docker compose exec web bin/rails runner 'User.find_by!(email: "[email protected]").update!(role: :super_admin)'
+```
+
+After that, you can promote other users at `/admin/users`. See section 3.5 of the [OIDC guide](oidc.md) for the console variant.
+
## How to change which updates your app receives
Set `SURE_IMAGE_TAG` in your `.env` file to a channel (`stable`, `latest`) or a specific version (for example `0.7.4`):
diff --git a/docs/hosting/oidc.md b/docs/hosting/oidc.md
index 91318c9073..b3d98b475e 100644
--- a/docs/hosting/oidc.md
+++ b/docs/hosting/oidc.md
@@ -194,6 +194,8 @@ User.find_by(email: "[email protected]").role # => "super_admin"
Once set, super‑admins can promote other users via the web UI at `/admin/users`.
+On self-hosted instances with more than one family, a `super_admin` is also required to change instance-wide settings (provider credentials, the shared AI connection settings, sync settings, the external assistant connection). Instances that predate automatic super-admin assignment should promote a user this way after upgrading.
+
---
## 4. Example configurations
diff --git a/test/controllers/settings/hostings_controller_test.rb b/test/controllers/settings/hostings_controller_test.rb
index c98e7d44b7..0c97ea3b42 100644
--- a/test/controllers/settings/hostings_controller_test.rb
+++ b/test/controllers/settings/hostings_controller_test.rb
@@ -5,6 +5,10 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
include ProviderTestHelper
setup do
+ # setting[...] values are instance-wide, so saving them takes a super
+ # admin. Promote the fixture admin rather than switching users so the
+ # family-scoped assertions below keep using dylan_family.
+ users(:family_admin).update!(role: :super_admin)
sign_in users(:family_admin)
@provider = mock
@@ -44,6 +48,78 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
assert_response :forbidden
end
+ test "a family admin cannot change instance-wide settings on an instance with several families" do
+ with_self_hosting do
+ sign_in users(:empty)
+
+ patch settings_hosting_url, params: { setting: {
+ openai_access_token: "attacker-token",
+ openai_uri_base: "https://attacker.example/v1",
+ openai_model: "gpt-4.1",
+ external_assistant_url: "https://attacker.example/agent"
+ } }
+
+ assert_redirected_to settings_hosting_url
+ assert_equal I18n.t("settings.hostings.not_authorized"), flash[:alert]
+ assert_nil Setting.openai_access_token
+ assert_nil Setting.external_assistant_url
+ assert_not_equal "https://attacker.example/v1", Setting.openai_uri_base
+ end
+ end
+
+ test "a family admin can still change their own family's assistant type" do
+ with_self_hosting do
+ sign_in users(:empty)
+
+ patch settings_hosting_url, params: { family: { assistant_type: "external" } }
+
+ assert_redirected_to settings_hosting_url
+ assert_equal "external", users(:empty).family.reload.assistant_type
+ end
+ end
+
+ test "a family admin cannot disconnect the instance's external assistant" do
+ Setting.external_assistant_url = "https://agent.example/v1"
+
+ with_self_hosting do
+ sign_in users(:empty)
+
+ delete disconnect_external_assistant_settings_hosting_url
+
+ assert_redirected_to settings_hosting_url
+ assert_equal I18n.t("settings.hostings.not_authorized"), flash[:alert]
+ assert_equal "https://agent.example/v1", Setting.external_assistant_url
+ end
+ end
+
+ test "a family admin sees why instance-wide settings are not offered" do
+ with_self_hosting do
+ sign_in users(:empty)
+
+ get settings_hosting_url
+
+ assert_response :success
+ assert_includes response.body, I18n.t("settings.hostings.show.instance_settings_restricted")
+ assert_select "form input[name^='setting[']", count: 0
+ assert_select "select[name='family[assistant_type]']"
+ end
+ end
+
+ test "the admin of the only family on a self-hosted instance can change instance-wide settings" do
+ with_self_hosting do
+ Family.stubs(:count).returns(1)
+ sign_in users(:empty)
+
+ patch settings_hosting_url, params: { setting: { twelve_data_api_key: "own-key" } }
+
+ assert_redirected_to settings_hosting_url
+ assert_equal "own-key", Setting.twelve_data_api_key
+
+ get settings_hosting_url
+ refute_includes response.body, I18n.t("settings.hostings.show.instance_settings_restricted")
+ end
+ end
+
test "should get edit when self hosting is enabled" do
@provider.expects(:usage).returns(@usage_response)
@@ -498,9 +574,10 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
# A gateway endpoint can carry its key in the userinfo or the query string,
# and `show` has no admin gate: any member who turns on preview features sees
- # this panel once the family's provider is Jev. Signed in as that member
- # rather than the admin, because that is who the endpoint must not reach.
- test "the jev panel shows a member the endpoint without its credentials" do
+ # the categorization panel once the family's provider is Jev. The Jev
+ # connection is an instance setting, so a member gets no field for it, and
+ # whoever manages it sees the endpoint without its credentials.
+ test "the jev panel shows a member neither the endpoint field nor its credentials" do
with_self_hosting do
Setting.jev_endpoint = "https://gw-user:[email protected]/v1/jev?api_key=qk-secret" # pipelock:ignore Credential in URL
member = users(:family_member)
@@ -511,8 +588,22 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
get settings_hosting_url
assert_response :success
- assert_select "input[name='setting[jev_endpoint]']", 1
- assert_select "input[name='setting[jev_endpoint]'][value='https://gw.example.com/v1/jev']"
+ assert_select "input[name='setting[jev_endpoint]']", 0
+ assert_no_match(/gw-secret|qk-secret|gw-user/, response.body)
+ end
+ end
+
+ test "the jev panel shows the instance settings manager the endpoint without its credentials" do
+ with_self_hosting do
+ Setting.jev_endpoint = "https://gw-user:[email protected]/v1/jev?api_key=qk-secret" # pipelock:ignore Credential in URL
+ admin = users(:family_admin)
+ admin.family.update!(categorization_provider: "jev")
+ admin.update!(preferences: (admin.preferences || {}).merge("preview_features_enabled" => true))
+
+ get settings_hosting_url
+
+ assert_response :success
+ assert_select "input[name='setting[jev_endpoint]'][value='https://gw.example.com/v1/jev']", 1
assert_no_match(/gw-secret|qk-secret|gw-user/, response.body)
end
end
diff --git a/test/controllers/settings/providers_controller_test.rb b/test/controllers/settings/providers_controller_test.rb
index 438b7daf54..a3e0813ef3 100644
--- a/test/controllers/settings/providers_controller_test.rb
+++ b/test/controllers/settings/providers_controller_test.rb
@@ -9,6 +9,10 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTest
# Exercise controller jobs independently of the daily login sync.
families(:dylan_family).update!(auto_sync_on_login: false)
ensure_tailwind_build
+ # Provider credentials are instance-wide, so saving them takes a super
+ # admin. Promote the fixture admin rather than switching users so the
+ # family-scoped assertions below keep using dylan_family.
+ users(:family_admin).update!(role: :super_admin)
sign_in users(:family_admin)
# Ensure provider adapters are loaded for all tests
@@ -150,6 +154,62 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to settings_providers_url
end
+ test "a family admin cannot change instance-wide provider credentials in managed mode" do
+ Rails.configuration.stubs(:app_mode).returns("managed".inquiry)
+ sign_in users(:empty)
+
+ patch settings_providers_url, params: { setting: { plaid_client_id: "attacker", plaid_secret: "attacker-secret" } }
+
+ assert_redirected_to settings_providers_url
+ assert_equal I18n.t("settings.providers.not_authorized"), flash[:alert]
+ assert_nil Setting["plaid_client_id"]
+ assert_nil Setting["plaid_secret"]
+ end
+
+ test "a family admin cannot change provider credentials on a self-hosted instance with several families" do
+ with_self_hosting do
+ sign_in users(:empty)
+
+ patch settings_providers_url, params: { setting: { plaid_client_id: "attacker" } }
+
+ assert_redirected_to settings_providers_url
+ assert_nil Setting["plaid_client_id"]
+ end
+ end
+
+ test "the admin of the only family on a self-hosted instance can change provider credentials" do
+ with_self_hosting do
+ Family.stubs(:count).returns(1)
+ sign_in users(:empty)
+
+ patch settings_providers_url, params: { setting: { plaid_client_id: "own-client-id" } }
+
+ assert_redirected_to settings_providers_url
+ assert_equal "own-client-id", Setting["plaid_client_id"]
+ end
+ ensure
+ Setting["plaid_client_id"] = nil
+ end
+
+ test "instance-wide provider forms are only offered to those who may save them" do
+ instance_wide_forms = Provider::ConfigurationRegistry.all.map do |config|
+ connect_form_settings_providers_path(provider_key: config.provider_key)
+ end
+
+ get settings_providers_url
+ assert instance_wide_forms.any? { |path| response.body.include?(path) }
+
+ sign_in users(:empty)
+
+ get settings_providers_url
+ assert_response :success
+ assert instance_wide_forms.none? { |path| response.body.include?(path) }
+
+ get connect_form_settings_providers_path(provider_key: "plaid")
+ assert_redirected_to settings_providers_path
+ assert_equal I18n.t("settings.providers.not_authorized"), flash[:alert]
+ end
+
test "should get show when self hosting is enabled" do
with_self_hosting do
get settings_providers_url
diff --git a/test/models/user_test.rb b/test/models/user_test.rb
index 286ad764ff..71e046e404 100644
--- a/test/models/user_test.rb
+++ b/test/models/user_test.rb
@@ -1063,6 +1063,28 @@ class UserTest < ActiveSupport::TestCase
assert_includes user.errors[:password], "can't be blank"
end
+ test "only a super admin manages instance settings when the instance hosts several families" do
+ assert Family.count > 1
+
+ assert users(:sure_support_staff).manages_instance_settings?
+ assert_not users(:family_admin).manages_instance_settings?
+ assert_not users(:family_member).manages_instance_settings?
+
+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)
+ assert_not users(:family_admin).manages_instance_settings?
+ end
+
+ test "the admins of the only family on a self-hosted instance manage instance settings" do
+ Family.stubs(:count).returns(1)
+
+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)
+ assert users(:family_admin).manages_instance_settings?
+ assert_not users(:family_member).manages_instance_settings?
+
+ Rails.configuration.stubs(:app_mode).returns("managed".inquiry)
+ assert_not users(:family_admin).manages_instance_settings?
+ end
+
# First user role assignment tests
test "role_for_new_family_creator returns super_admin when no users exist" do
# Delete all users to simulate fresh instance
diff --git a/test/system/settings/categorization_provider_test.rb b/test/system/settings/categorization_provider_test.rb
index 47003214cc..44ee9adfef 100644
--- a/test/system/settings/categorization_provider_test.rb
+++ b/test/system/settings/categorization_provider_test.rb
@@ -91,6 +91,8 @@ class Settings::CategorizationProviderTest < ApplicationSystemTestCase
# The key field used to live in a separate panel below, so an operator could
# enter a key and have nothing happen. Selecting the provider and giving it
# a key are one task and belong in one place.
+ # The credentials are instance-wide, so only a super admin is offered them.
+ @user.update!(role: :super_admin)
set_preview_features(true)
visit settings_hosting_path
diff --git a/test/system/settings/providers_test.rb b/test/system/settings/providers_test.rb
index c5940f2352..27d5f64094 100644
--- a/test/system/settings/providers_test.rb
+++ b/test/system/settings/providers_test.rb
@@ -5,6 +5,10 @@ class Settings::ProvidersTest < ApplicationSystemTestCase
include FinancekitTestHelper
setup do
@user = users(:family_admin)
+ # Registry-driven provider forms (Plaid) edit instance-wide credentials and
+ # are only shown to a super admin; promote the fixture admin so the family
+ # panels below keep using dylan_family.
+ @user.update!(role: :super_admin)
@family = families(:dylan_family)
login_as @user
end