The personal finance app for everyone (by everyone)
Ruby
Let self-hosted super admins opt into the demo family refresh (#3859)
Juan José Mata31323d167676
diff --git a/app/controllers/settings/hostings_controller.rb b/app/controllers/settings/hostings_controller.rbindex 09c1e8d16c..53cf185fb2 100644--- a/app/controllers/settings/hostings_controller.rb+++ b/app/controllers/settings/hostings_controller.rb@@ -65,6 +65,29 @@ class Settings::HostingsController < ApplicationControllerSetting.onboarding_state = onboarding_stateend+ if hosting_params.key?(:demo_family_refresh_enabled) || hosting_params.key?(:demo_family_refresh_family_id)+ unless Current.user.super_admin?+ return redirect_to settings_hosting_path, alert: t(".not_authorized")+ end+ if hosting_params.key?(:demo_family_refresh_family_id)+ family_id = hosting_params[:demo_family_refresh_family_id].presence+ demo_email = Rails.application.config_for(:demo).with_indifferent_access.fetch(:email)+ unless family_id.nil? || User.admin.exists?(family_id: family_id, email: demo_email) && !User.super_admin.exists?(family_id: family_id)+ raise Setting::ValidationError, t(".invalid_demo_family")+ end+ if family_id.nil? && Setting.demo_family_refresh_enabled && hosting_params[:demo_family_refresh_enabled] != "0"+ raise Setting::ValidationError, t(".select_demo_family")+ end+ Setting.demo_family_refresh_family_id = family_id+ end+ if hosting_params.key?(:demo_family_refresh_enabled)+ if hosting_params[:demo_family_refresh_enabled] == "1" && Setting.demo_family_refresh_family_id.blank?+ raise Setting::ValidationError, t(".select_demo_family")+ end+ Setting.demo_family_refresh_enabled = hosting_params[:demo_family_refresh_enabled] == "1"+ end+ end+if hosting_params.key?(:require_email_confirmation)Setting.require_email_confirmation = hosting_params[:require_email_confirmation]end@@ -300,7 +323,7 @@ class Settings::HostingsController < ApplicationController# Strong parameters for the self-hosting settings form.def hosting_paramsreturn ActionController::Parameters.new unless params.key?(:setting)- params.require(:setting).permit(:onboarding_state, :require_email_confirmation, :invite_only_default_family_id, :brand_fetch_client_id, :brand_fetch_high_res_logos, :twelve_data_api_key, :tiingo_api_key, :eodhd_api_key, :alpha_vantage_api_key, :tinkoff_invest_api_key, :mansa_api_key, :rentcast_api_key, :realie_api_key, :openai_access_token, :openai_uri_base, :openai_model, :openai_json_mode, :anthropic_access_token, :anthropic_base_url, :anthropic_model, :jev_api_key, :jev_endpoint, :jev_model, :llm_provider, :llm_context_window, :llm_max_response_tokens, :llm_max_items_per_call, :openai_request_timeout, :ai_response_timeout, :exchange_rate_provider, :securities_provider, :syncs_include_pending, :auto_sync_enabled, :auto_sync_time, :external_assistant_url, :external_assistant_token, :external_assistant_model, securities_providers: [])+ params.require(:setting).permit(:onboarding_state, :require_email_confirmation, :invite_only_default_family_id, :demo_family_refresh_enabled, :demo_family_refresh_family_id, :brand_fetch_client_id, :brand_fetch_high_res_logos, :twelve_data_api_key, :tiingo_api_key, :eodhd_api_key, :alpha_vantage_api_key, :tinkoff_invest_api_key, :mansa_api_key, :rentcast_api_key, :realie_api_key, :openai_access_token, :openai_uri_base, :openai_model, :openai_json_mode, :anthropic_access_token, :anthropic_base_url, :anthropic_model, :jev_api_key, :jev_endpoint, :jev_model, :llm_provider, :llm_context_window, :llm_max_response_tokens, :llm_max_items_per_call, :openai_request_timeout, :ai_response_timeout, :exchange_rate_provider, :securities_provider, :syncs_include_pending, :auto_sync_enabled, :auto_sync_time, :external_assistant_url, :external_assistant_token, :external_assistant_model, securities_providers: [])enddef load_external_assistant_modelsdiff --git a/app/jobs/demo_family_refresh_job.rb b/app/jobs/demo_family_refresh_job.rbindex 42402f77a7..f52a118ea3 100644--- a/app/jobs/demo_family_refresh_job.rb+++ b/app/jobs/demo_family_refresh_job.rb@@ -3,10 +3,10 @@ class DemoFamilyRefreshJob < ApplicationJobsidekiq_options retry: falsedef perform- return unless Rails.application.config.app_mode.managed?+ return unless Rails.application.config.app_mode.managed? || Setting.demo_family_refresh_enabledwith_advisory_lock do- refresh_demo_family+ refresh_demo_family if Rails.application.config.app_mode.managed? || Setting.demo_family_refresh_enabledendend@@ -19,6 +19,19 @@ class DemoFamilyRefreshJob < ApplicationJobdemo_user = User.find_by(email: demo_email)old_family = demo_user&.family+ if Rails.application.config.app_mode.self_hosted?+ # Email alone is not proof that a family is disposable. An administrator+ # must explicitly enroll the family whose data will be replaced.+ configured_id = Setting.demo_family_refresh_family_id.presence+ return Rails.logger.warn("Skipped demo family refresh: no family selected") unless configured_id+ return Rails.logger.warn("Skipped demo family refresh: selected family does not have a demo admin") unless demo_user&.role == "admin" && old_family.id.to_s == configured_id.to_s && !old_family.users.super_admin.exists?++ # The generator transfers this global key to the new demo user. Never+ # take it away from a different family on a self-hosted instance.+ monitoring_key = ApiKey.find_by(display_key: ApiKey::DEMO_MONITORING_KEY)+ return Rails.logger.warn("Skipped demo family refresh: monitoring key belongs to another family") if monitoring_key && monitoring_key.user.family_id != old_family.id+ end+old_family_session_count = sessions_count_for(old_family, period_start:, period_end:)newly_created_families_count = Family.where(created_at: period_start...period_end).count@@ -28,6 +41,11 @@ class DemoFamilyRefreshJob < ApplicationJobendDemo::Generator.new.generate_default_data!(skip_clear: true, email: demo_email)+ if Rails.application.config.app_mode.self_hosted?+ new_family = User.find_by!(email: demo_email).family+ Setting.demo_family_refresh_family_id = new_family.id.to_s+ retire_old_family!(old_family) if old_family+ endendDestroyJob.perform_later(old_family) if old_family@@ -41,6 +59,26 @@ class DemoFamilyRefreshJob < ApplicationJob)end+ # Retiring a demo family must close access before its asynchronous deletion.+ # Deletion can fail on unrelated callbacks, and anonymizing email alone+ # leaves sessions and keys usable. The generator transfers the dedicated+ # monitoring key to the replacement before this runs.+ def retire_old_family!(family)+ family.users.find_each do |user|+ SsoIdentityBlock.block_all!(user.oidc_identities, identity_label: user.email)+ user.sessions.delete_all+ user.api_keys.active.visible.update_all(revoked_at: Time.current)+ Doorkeeper::AccessToken.where(resource_owner_id: user.id, revoked_at: nil).update_all(revoked_at: Time.current)+ Doorkeeper::AccessGrant.where(resource_owner_id: user.id, revoked_at: nil).update_all(revoked_at: Time.current)+ user.update_columns(active: false)+ end++ # The generator's synthetic subscription is not a real Stripe object.+ # Mark it canceled so Family's destroy callback does not try Stripe.+ subscription = family.subscription+ subscription.update!(status: :canceled) if subscription&.stripe_id == "sub_demo_123"+ end+def sessions_count_for(family, period_start:, period_end:)return 0 unless familydiff --git a/app/models/setting.rb b/app/models/setting.rbindex b7de3f3b42..dc47539fbf 100644--- a/app/models/setting.rb+++ b/app/models/setting.rb@@ -208,6 +208,9 @@ class Setting < RailsSettings::Basefield :require_invite_for_signup, type: :boolean, default: falsefield :require_email_confirmation, type: :boolean, default: ENV.fetch("REQUIRE_EMAIL_CONFIRMATION", "true") == "true"field :invite_only_default_family_id, type: :string, default: nil+ # Opt-in for self-hosted demo refresh. Managed hosting retains its scheduled behavior.+ field :demo_family_refresh_enabled, type: :boolean, default: false+ field :demo_family_refresh_family_id, type: :string, default: nildef self.validate_onboarding_state!(state)return if ONBOARDING_STATES.include?(state)diff --git a/app/views/settings/hostings/_demo_refresh_settings.html.erb b/app/views/settings/hostings/_demo_refresh_settings.html.erbnew file mode 100644index 0000000000..1ba3d8c3b8--- /dev/null+++ b/app/views/settings/hostings/_demo_refresh_settings.html.erb@@ -0,0 +1,25 @@+<div class="space-y-4">+ <p class="text-sm text-secondary"><%= t(".description") %></p>+ <%= styled_form_with model: Setting.new,+ url: settings_hosting_path,+ method: :patch,+ class: "space-y-4" do |form| %>+ <%= form.select :demo_family_refresh_family_id,+ options_for_select([[t(".none"), ""]] ++ Family.joins(:users).where(users: { email: Rails.application.config_for(:demo).with_indifferent_access.fetch(:email), role: :admin }).where.not(id: User.super_admin.select(:family_id)).distinct.map { |family| ["#{family.name} (##{family.id})", family.id] },+ Setting.demo_family_refresh_family_id),+ { label: t(".family_label") } %>+ <%= form.submit t(".save_family") %>+ <% end %>+ <%= styled_form_with model: Setting.new,+ url: settings_hosting_path,+ method: :patch,+ data: { controller: "auto-submit-form", auto_submit_form_trigger_event_value: "change" } do |form| %>+ <div class="flex items-center justify-between gap-4">+ <span class="text-sm"><%= t(".enabled_label") %></span>+ <%= form.toggle :demo_family_refresh_enabled,+ checked: Setting.demo_family_refresh_enabled,+ data: { auto_submit_form_target: "auto" } %>+ </div>+ <% end %>+</div>diff --git a/app/views/settings/hostings/show.html.erb b/app/views/settings/hostings/show.html.erbindex d410c9d791..4003929e8c 100644--- a/app/views/settings/hostings/show.html.erb+++ b/app/views/settings/hostings/show.html.erb@@ -71,6 +71,11 @@<%= render "settings/hostings/invite_code_settings" %><% end %><% end %>+<% if Current.user.super_admin? %>+ <%= settings_section title: t(".demo_refresh") do %>+ <%= render "settings/hostings/demo_refresh_settings" %>+ <% end %>+<% end %><%= settings_section title: t(".danger_zone") do %><%= render "settings/hostings/danger_zone_settings" %><% end %>diff --git a/config/locales/views/settings/hostings/en.yml b/config/locales/views/settings/hostings/en.ymlindex b337694979..e4ad2cc745 100644--- a/config/locales/views/settings/hostings/en.yml+++ b/config/locales/views/settings/hostings/en.yml@@ -17,7 +17,14 @@ en:open: Openclosed: Closedinvite_only: Invite-only+ demo_refresh_settings:+ description: "Automatically refresh only the selected demo family. All its data and logins will be removed. Other families are untouched. Requires a running worker with at least 2 GiB RAM. First create a disposable demo family using the demo generator, then select it here. Do not choose a real user's family."+ none: No demo family selected+ family_label: Disposable demo family+ save_family: Save demo family+ enabled_label: Enable daily demo family refreshshow:+ demo_refresh: Demo data refreshgeneral: General Settingsai_assistant: AI Assistantfinancial_data_providers: Financial Data Providers@@ -297,6 +304,8 @@ en:view_pricing: View Twelve Data pricingtitle: Twelve Dataupdate:+ invalid_demo_family: Selected family must own the configured demo email.+ select_demo_family: Select a disposable demo family first.failure: Invalid setting valuesuccess: Settings updatedinvalid_onboarding_state: Invalid onboarding statediff --git a/test/controllers/settings/hostings_controller_test.rb b/test/controllers/settings/hostings_controller_test.rbindex f0d1708527..16a4ca8313 100644--- a/test/controllers/settings/hostings_controller_test.rb+++ b/test/controllers/settings/hostings_controller_test.rb@@ -27,7 +27,7 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTestteardown do# These tests persist global Setting.* values; reset them so state can't# leak into later (order-dependent) tests.- %i[anthropic_access_token anthropic_base_url anthropic_model jev_api_key jev_endpoint jev_model llm_provider twelve_data_api_key openai_access_token openai_request_timeout ai_response_timeout external_assistant_url external_assistant_token external_assistant_model external_assistant_agent_id rentcast_api_key realie_api_key].each do |key|+ %i[anthropic_access_token anthropic_base_url anthropic_model jev_api_key jev_endpoint jev_model llm_provider twelve_data_api_key openai_access_token openai_request_timeout ai_response_timeout external_assistant_url external_assistant_token external_assistant_model external_assistant_agent_id rentcast_api_key realie_api_key demo_family_refresh_enabled demo_family_refresh_family_id].each do |key|Setting.public_send("#{key}=", nil)endend@@ -84,6 +84,76 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTestendend+ test "only a super admin can opt in and the selected family must own the demo email" do+ # The configured demo email is already used by the new_email fixture.+ demo_email = "[email protected]"+ Rails.application.stubs(:config_for).with(:demo).returns({ email: demo_email })++ with_self_hosting do+ patch settings_hosting_url, params: { setting: { demo_family_refresh_enabled: "1" } }+ assert_not Setting.demo_family_refresh_enabled++ sign_in users(:sure_support_staff)+ patch settings_hosting_url, params: { setting: { demo_family_refresh_enabled: "1" } }+ assert_response :unprocessable_entity+ assert_not Setting.demo_family_refresh_enabled++ family = families(:dylan_family)+ patch settings_hosting_url, params: { setting: { demo_family_refresh_family_id: family.id } }+ assert_response :unprocessable_entity++ demo_family = Family.create!(name: "Disposable Demo")+ demo_family.users.create!(first_name: "Demo", last_name: "Owner", email: demo_email, password: "password123", role: :admin)+ patch settings_hosting_url, params: { setting: { demo_family_refresh_family_id: demo_family.id } }+ assert_redirected_to settings_hosting_path+ patch settings_hosting_url, params: { setting: { demo_family_refresh_enabled: "1" } }+ assert Setting.demo_family_refresh_enabled+ end+ end++ test "demo family selection excludes non-admin email owners and cannot be cleared while enabled" do+ demo_email = "[email protected]"+ Rails.application.stubs(:config_for).with(:demo).returns({ email: demo_email })+ demo_family = Family.create!(name: "Demo Selection")+ demo_user = demo_family.users.create!(first_name: "Demo", last_name: "Member", email: demo_email, password: "password123", role: :member)+ sign_in users(:sure_support_staff)++ with_self_hosting do+ get settings_hosting_url+ assert_response :success+ assert_select "option[value='#{demo_family.id}']", count: 0++ patch settings_hosting_url, params: { setting: { demo_family_refresh_family_id: demo_family.id } }+ assert_response :unprocessable_entity+ assert_nil Setting.demo_family_refresh_family_id++ demo_user.update!(role: :super_admin)+ get settings_hosting_url+ assert_select "option[value='#{demo_family.id}']", count: 0+ demo_user.update!(role: :admin)+ other_admin = demo_family.users.create!(first_name: "Instance", last_name: "Admin", email: "[email protected]", password: "password123", role: :super_admin)+ get settings_hosting_url+ assert_select "option[value='#{demo_family.id}']", count: 0+ other_admin.update!(role: :member)+ get settings_hosting_url+ assert_select "option[value='#{demo_family.id}']", count: 1+ patch settings_hosting_url, params: { setting: { demo_family_refresh_family_id: demo_family.id } }+ assert_redirected_to settings_hosting_path+ patch settings_hosting_url, params: { setting: { demo_family_refresh_enabled: "1" } }+ assert Setting.demo_family_refresh_enabled++ patch settings_hosting_url, params: { setting: { demo_family_refresh_family_id: "" } }+ assert_response :unprocessable_entity+ assert_equal demo_family.id.to_s, Setting.demo_family_refresh_family_id+ assert Setting.demo_family_refresh_enabled++ patch settings_hosting_url, params: { setting: { demo_family_refresh_family_id: "", demo_family_refresh_enabled: "0" } }+ assert_redirected_to settings_hosting_path+ assert_nil Setting.demo_family_refresh_family_id+ assert_not Setting.demo_family_refresh_enabled+ end+ end+test "can update rentcast api key when self hosting is enabled" dowith_self_hosting dopatch settings_hosting_url, params: { setting: { rentcast_api_key: "rentcast-token" } }diff --git a/test/jobs/demo_family_refresh_job_test.rb b/test/jobs/demo_family_refresh_job_test.rbindex b638531749..45dae4c622 100644--- a/test/jobs/demo_family_refresh_job_test.rb+++ b/test/jobs/demo_family_refresh_job_test.rb@@ -72,6 +72,122 @@ class DemoFamilyRefreshJobTest < ActiveJob::TestCaseDemoFamilyRefreshJob.perform_nowend+ test "self-hosted refresh is disabled by default" do+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)+ Setting.demo_family_refresh_enabled = false+ Demo::Generator.expects(:new).never++ DemoFamilyRefreshJob.perform_now+ assert_equal @demo_email, @demo_user.reload.email+ end++ test "self-hosted refresh replaces only the explicitly selected demo family" do+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)+ visitor = Family.create!(name: "Visitor")+ visitor_user = visitor.users.create!(first_name: "Visitor", last_name: "Owner", email: "[email protected]", password: "password123", role: :admin)+ Setting.demo_family_refresh_family_id = @demo_family.id.to_s+ Setting.demo_family_refresh_enabled = true++ generator = mock+ generator.expects(:generate_default_data!).with do |options|+ assert_equal({ skip_clear: true, email: @demo_email }, options)+ new_family = Family.create!(name: "Fresh Demo")+ new_family.users.create!(first_name: "New", last_name: "Demo", email: @demo_email, password: "password123", role: :admin)+ end+ Demo::Generator.expects(:new).returns(generator)++ assert_enqueued_with(job: DestroyJob, args: [ @demo_family ]) do+ DemoFamilyRefreshJob.perform_now+ end+ assert_equal visitor.id, visitor_user.reload.family_id+ assert_equal User.find_by!(email: @demo_email).family_id.to_s, Setting.demo_family_refresh_family_id+ ensure+ Setting.demo_family_refresh_enabled = false+ Setting.demo_family_refresh_family_id = nil+ end++ test "self-hosted refresh revokes old credentials and disarms the synthetic subscription" do+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)+ Setting.demo_family_refresh_family_id = @demo_family.id.to_s+ Setting.demo_family_refresh_enabled = true+ @demo_family.start_subscription!("sub_demo_123")+ session = Session.create!(user: @demo_user)+ app = Doorkeeper::Application.create!(name: "Demo Retirement Test", redirect_uri: "https://example.com/callback", confidential: false)+ token = Doorkeeper::AccessToken.create!( # pipelock:ignore Credential in URL+ application: app, resource_owner_id: @demo_user.id, scopes: "read", expires_in: 1.year)+ grant = Doorkeeper::AccessGrant.create!(application: app, resource_owner_id: @demo_user.id, redirect_uri: app.redirect_uri, expires_in: 10.minutes, scopes: "read")+ key = @demo_user.api_keys.create!(name: "visitor", key: "old-demo-visitor-key", scopes: [ "read" ], source: "web")++ generator = mock+ generator.expects(:generate_default_data!).with(skip_clear: true, email: @demo_email) do+ new_family = Family.create!(name: "Replacement Demo")+ new_family.users.create!(first_name: "New", last_name: "Demo", email: @demo_email, password: "password123", role: :admin)+ end+ Demo::Generator.expects(:new).returns(generator)+ Provider::Registry.expects(:get_provider).with(:stripe).never++ assert_enqueued_with(job: DestroyJob, args: [ @demo_family ]) do+ DemoFamilyRefreshJob.perform_now+ end+ assert_not @demo_user.reload.active?+ assert_not Session.exists?(session.id)+ assert key.reload.revoked?+ assert token.reload.revoked_at+ assert grant.reload.revoked_at+ assert @demo_family.reload.subscription.canceled?+ assert @demo_family.destroy+ ensure+ Setting.demo_family_refresh_enabled = false+ Setting.demo_family_refresh_family_id = nil+ end++ test "self-hosted refresh refuses a family mismatch or a monitoring key owned by another family" do+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)+ Setting.demo_family_refresh_enabled = true+ Setting.demo_family_refresh_family_id = families(:dylan_family).id.to_s+ Demo::Generator.expects(:new).never+ DemoFamilyRefreshJob.perform_now+ assert_equal @demo_email, @demo_user.reload.email++ Setting.demo_family_refresh_family_id = @demo_family.id.to_s+ @super_admin.api_keys.create!(name: "monitoring", key: ApiKey::DEMO_MONITORING_KEY, scopes: [ "read" ], source: "monitoring")+ DemoFamilyRefreshJob.perform_now+ assert_equal @demo_email, @demo_user.reload.email+ ensure+ Setting.demo_family_refresh_enabled = false+ Setting.demo_family_refresh_family_id = nil+ end++ test "self-hosted refresh refuses a selected family whose demo user lost admin access" do+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)+ Setting.demo_family_refresh_family_id = @demo_family.id.to_s+ Setting.demo_family_refresh_enabled = true+ @demo_user.update!(role: :member)+ Demo::Generator.expects(:new).never++ assert_no_enqueued_jobs do+ DemoFamilyRefreshJob.perform_now+ end+ assert_equal @demo_email, @demo_user.reload.email+ ensure+ Setting.demo_family_refresh_enabled = false+ Setting.demo_family_refresh_family_id = nil+ end++ test "self-hosted refresh refuses a selected family containing a super admin" do+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)+ Setting.demo_family_refresh_family_id = @demo_family.id.to_s+ Setting.demo_family_refresh_enabled = true+ @demo_family.users.create!(first_name: "Instance", last_name: "Admin", email: "[email protected]", password: "password123", role: :super_admin)+ Demo::Generator.expects(:new).never++ assert_no_enqueued_jobs { DemoFamilyRefreshJob.perform_now }+ assert_equal @demo_email, @demo_user.reload.email+ ensure+ Setting.demo_family_refresh_enabled = false+ Setting.demo_family_refresh_family_id = nil+ end+test "does not retry after a failed refresh" doassert_equal false, DemoFamilyRefreshJob.sidekiq_options_hash["retry"]end