OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
stringify hash settings keys and support OPENPROJECT_2FA env var
Christophe Bliard2c67f992a546
diff --git a/app/models/setting.rb b/app/models/setting.rbindex 9ccab7b9362..cc0e524d1da 100644--- a/app/models/setting.rb+++ b/app/models/setting.rb@@ -326,6 +326,7 @@ class Setting < ApplicationRecordif definition.serialized? && value.is_a?(String)YAML::safe_load(value, permitted_classes: [Symbol, ActiveSupport::HashWithIndifferentAccess, Date, Time])+ .tap { |maybe_hash| maybe_hash.try(:deep_stringify_keys!) }elsif value != '' && !value.nil?read_formatted_setting(value, definition.format)elsediff --git a/config/constants/settings/definition.rb b/config/constants/settings/definition.rbindex d92d1f86c8d..505350dd25f 100644--- a/config/constants/settings/definition.rb+++ b/config/constants/settings/definition.rb@@ -31,7 +31,8 @@ module SettingsENV_PREFIX = 'OPENPROJECT_'.freezeattr_accessor :name,- :format+ :format,+ :env_aliasattr_writer :value,:allowed@@ -40,12 +41,14 @@ module Settingsvalue:,format: nil,writable: true,- allowed: nil)+ allowed: nil,+ env_alias: nil)self.name = name.to_sself.format = format ? format.to_sym : deduce_format(value)- self.value = value+ self.value = value.is_a?(Hash) ? value.deep_stringify_keys : valueself.writable = writableself.allowed = allowed+ self.env_alias = env_aliasenddef value@@ -84,7 +87,7 @@ module Settingsdef override_value(other_value)if format == :hashself.value = {} if value.nil?- value.deep_merge! other_value+ value.deep_merge! other_value.deep_stringify_keyselseself.value = other_valueend@@ -131,7 +134,8 @@ module Settingsvalue:,format: nil,writable: true,- allowed: nil)+ allowed: nil,+ env_alias: nil)return if @by_name.present? && @by_name[name.to_s].present?@by_name = nil@@ -140,7 +144,8 @@ module Settingsformat: format,value: value,writable: writable,- allowed: allowed)+ allowed: allowed,+ env_alias: env_alias)override_value(definition)@@ -324,8 +329,9 @@ module Settings[env_name_legacy(definition),env_name(definition),- env_name_unprefixed(definition)- ]+ env_name_unprefixed(definition),+ env_name_alias(definition)+ ].compactenddef env_name_legacy(definition)@@ -340,6 +346,10 @@ module Settingsdefinition.name.upcaseend+ def env_name_alias(definition)+ "#{ENV_PREFIX}#{definition.env_alias.upcase}" if definition.env_alias+ end+### Extract the configuration value from the given environment variable# using YAML.diff --git a/lib/redmine/plugin.rb b/lib/redmine/plugin.rbindex 1d9860d3f28..b8b47dd81aa 100644--- a/lib/redmine/plugin.rb+++ b/lib/redmine/plugin.rb@@ -109,7 +109,8 @@ module Redmine #:nodoc:if p.settingsSettings::Definition.add("plugin_#{id}",value: p.settings[:default],- format: :hash)+ format: :hash,+ env_alias: p.settings[:env_alias])end# If there are plugins waiting for us to be loaded, we try loading those, againdiff --git a/modules/ldap_groups/lib/open_project/ldap_groups/engine.rb b/modules/ldap_groups/lib/open_project/ldap_groups/engine.rbindex 1392e510e06..99fa437f9c9 100644--- a/modules/ldap_groups/lib/open_project/ldap_groups/engine.rb+++ b/modules/ldap_groups/lib/open_project/ldap_groups/engine.rb@@ -8,9 +8,7 @@ module OpenProject::LdapGroupsauthor_url: 'https://github.com/opf/openproject-ldap_groups',bundled: true,settings: {- default: {- name_attribute: 'cn'- }+ default: {}} domenu :admin_menu,:plugin_ldap_groups,diff --git a/modules/recaptcha/app/controllers/recaptcha/request_controller.rb b/modules/recaptcha/app/controllers/recaptcha/request_controller.rbindex 5bb7c9376c5..db5628a7fe2 100644--- a/modules/recaptcha/app/controllers/recaptcha/request_controller.rb+++ b/modules/recaptcha/app/controllers/recaptcha/request_controller.rb@@ -46,7 +46,7 @@ module ::Recaptchaenddef recaptcha_version- case recaptcha_settings[:recaptcha_type]+ case recaptcha_settings['recaptcha_type']when ::OpenProject::Recaptcha::TYPE_DISABLED0when ::OpenProject::Recaptcha::TYPE_V2@@ -59,7 +59,7 @@ module ::Recaptcha###def valid_recaptcha?- call_args = { secret_key: recaptcha_settings[:secret_key] }+ call_args = { secret_key: recaptcha_settings['secret_key'] }if recaptcha_version == 3call_args[:action] = 'login'end@@ -88,7 +88,7 @@ module ::Recaptchaenddef skip_if_disabled- if recaptcha_settings[:recaptcha_type] == ::OpenProject::Recaptcha::TYPE_DISABLED+ if recaptcha_settings['recaptcha_type'] == ::OpenProject::Recaptcha::TYPE_DISABLEDcomplete_stage_redirectendend@@ -100,7 +100,7 @@ module ::Recaptchaenddef skip_if_user_verified- if ::Recaptcha::Entry.where(user_id: @authenticated_user.id).exists?+ if ::Recaptcha::Entry.exists?(user_id: @authenticated_user.id)Rails.logger.debug { "User #{@authenticated_user.id} already provided recaptcha. Skipping. " }complete_stage_redirectenddiff --git a/modules/recaptcha/app/views/recaptcha/admin/show.html.erb b/modules/recaptcha/app/views/recaptcha/admin/show.html.erbindex 74dc19311d9..2b34061af8b 100644--- a/modules/recaptcha/app/views/recaptcha/admin/show.html.erb+++ b/modules/recaptcha/app/views/recaptcha/admin/show.html.erb@@ -12,7 +12,7 @@<label class="form--label" for='recaptcha_type'><%= t('recaptcha.settings.type') %></label><div class="form--field-container"><%= styled_select_tag 'recaptcha_type',- options_for_select(recaptcha_available_options, Setting.plugin_openproject_recaptcha[:recaptcha_type]),+ options_for_select(recaptcha_available_options, Setting.plugin_openproject_recaptcha['recaptcha_type']),container_class: '-middle' %></div><div class="form--field-instructions">@@ -24,7 +24,7 @@<label class="form--label" for='website_key'><%= t('recaptcha.settings.website_key') %></label><div class="form--field-container"><%= styled_text_field_tag 'website_key',- Setting.plugin_openproject_recaptcha[:website_key] %>+ Setting.plugin_openproject_recaptcha['website_key'] %></div><div class="form--field-instructions"><%= I18n.t('recaptcha.settings.website_key_text') %>@@ -34,7 +34,7 @@<label class="form--label" for='secret_key'><%= t('recaptcha.settings.secret_key') %></label><div class="form--field-container"><%= styled_text_field_tag 'secret_key',- Setting.plugin_openproject_recaptcha[:secret_key] %>+ Setting.plugin_openproject_recaptcha['secret_key'] %></div><div class="form--field-instructions"><%= I18n.t('recaptcha.settings.secret_key_text') %>diff --git a/modules/recaptcha/app/views/recaptcha/request/perform.html.erb b/modules/recaptcha/app/views/recaptcha/request/perform.html.erbindex 2825596ae20..98901554047 100644--- a/modules/recaptcha/app/views/recaptcha/request/perform.html.erb+++ b/modules/recaptcha/app/views/recaptcha/request/perform.html.erb@@ -3,13 +3,13 @@<div id="login-form" class="form -bordered"><%= styled_form_tag({ action: :verify }, { :autocomplete => "off", :id => 'submit_captcha' }) do %><h2><%= t 'recaptcha.verify_account' %></h2>- <% if recaptcha_settings[:recaptcha_type] == ::OpenProject::Recaptcha::TYPE_V2 %>+ <% if recaptcha_settings['recaptcha_type'] == ::OpenProject::Recaptcha::TYPE_V2 %><% input_name = "g-recaptcha-response" %><input type="hidden" name="<%= input_name %>" /><%= recaptcha_tags(nonce: content_security_policy_script_nonce,callback: 'submitRecaptchaForm',- site_key: recaptcha_settings[:website_key]+ site_key: recaptcha_settings['website_key']) %><%= nonced_javascript_tag do %>@@ -28,11 +28,11 @@document.getElementById('submit_captcha').submit();}<% end %>- <% elsif recaptcha_settings[:recaptcha_type] == ::OpenProject::Recaptcha::TYPE_V3 %>+ <% elsif recaptcha_settings['recaptcha_type'] == ::OpenProject::Recaptcha::TYPE_V3 %><%= recaptcha_v3 action: 'login',nonce: content_security_policy_script_nonce,callback: 'submitRecaptchaForm',- site_key: recaptcha_settings[:website_key] %>+ site_key: recaptcha_settings['website_key'] %><p><%= t('recaptcha.button_please_wait') %></p><%= nonced_javascript_tag do %>diff --git a/modules/recaptcha/lib/open_project/recaptcha/engine.rb b/modules/recaptcha/lib/open_project/recaptcha/engine.rbindex 3afb87acc28..e845dfeda8b 100644--- a/modules/recaptcha/lib/open_project/recaptcha/engine.rb+++ b/modules/recaptcha/lib/open_project/recaptcha/engine.rb@@ -23,7 +23,7 @@ module OpenProject::Recaptchaendconfig.after_initialize do- SecureHeaders::Configuration.named_append(:recaptcha) do |request|+ SecureHeaders::Configuration.named_append(:recaptcha) doif OpenProject::Recaptcha.use_hcaptcha?value = %w(https://*.hcaptcha.com)keys = %i(frame_src script_src style_src connect_src)@@ -41,7 +41,7 @@ module OpenProject::Recaptchanil,run_after_activation: true,active: -> {- type = Setting.plugin_openproject_recaptcha[:recaptcha_type]+ type = Setting.plugin_openproject_recaptcha['recaptcha_type']type.present? && type.to_s != ::OpenProject::Recaptcha::TYPE_DISABLED}diff --git a/modules/two_factor_authentication/app/models/two_factor_authentication/device/totp.rb b/modules/two_factor_authentication/app/models/two_factor_authentication/device/totp.rbindex e6716994ddd..94cd8f924ba 100644--- a/modules/two_factor_authentication/app/models/two_factor_authentication/device/totp.rb+++ b/modules/two_factor_authentication/app/models/two_factor_authentication/device/totp.rb@@ -57,7 +57,7 @@ module TwoFactorAuthenticationenddef allowed_drift- self.class.manager.configuration.fetch :otp_drift_window, 60+ self.class.manager.configuration['otp_drift_window'] || 60enddef totpdiff --git a/modules/two_factor_authentication/app/views/two_factor_authentication/settings.html.erb b/modules/two_factor_authentication/app/views/two_factor_authentication/settings.html.erbindex 3bfe414c81a..77ee8915122 100644--- a/modules/two_factor_authentication/app/views/two_factor_authentication/settings.html.erb+++ b/modules/two_factor_authentication/app/views/two_factor_authentication/settings.html.erb@@ -19,8 +19,8 @@<div class="attributes-key-value--key"><%= t('two_factor_authentication.settings.label_active_strategies') %></div><div class="attributes-key-value--value-container"><div class="attributes-key-value--value">- <%= t(:label_none) if configuration[:active_strategies].empty? %>- <% configuration[:active_strategies].each do |key| %>+ <%= t(:label_none) if configuration['active_strategies'].empty? %>+ <% configuration['active_strategies'].each do |key| %><span><%= t("two_factor_authentication.strategies.#{key}") %></span>@@ -31,16 +31,16 @@<div class="attributes-key-value--key"><%= t('two_factor_authentication.settings.label_enforced') %></div><div class="attributes-key-value--value-container"><div class="attributes-key-value--value">- <span><%= !!configuration[:enforced] %></span>+ <span><%= !!configuration['enforced'] %></span></div></div><div class="attributes-key-value--key"><%= t('two_factor_authentication.settings.label_remember') %></div><div class="attributes-key-value--value-container"><div class="attributes-key-value--value">- <% if configuration[:allow_remember_for_days].to_i == 0 %>+ <% if configuration['allow_remember_for_days'].to_i == 0 %><span><%= t(:label_disabled) %></span><% else %>- <span><%= configuration[:allow_remember_for_days] %> (<%= t(:label_day_plural) %>)</span>+ <span><%= configuration['allow_remember_for_days'] %> (<%= t(:label_day_plural) %>)</span><% end %></div></div>@@ -53,8 +53,8 @@<div class="form--field-container "><%= styled_check_box_tag 'settings[enforced]','1',- !!configuration[:enforced],- disabled: strategy_manager.enforced_by_configuration? || configuration[:active_strategies].empty?,+ !!configuration['enforced'],+ disabled: strategy_manager.enforced_by_configuration? || configuration['active_strategies'].empty?,container_class: '-middle' %></div><div class="form--field-instructions">@@ -65,7 +65,7 @@<label class="form--label" for='settings[allow_remember_for_days]'><%= t('two_factor_authentication.settings.label_remember') %></label><div class="form--field-container"><%= styled_number_field_tag 'settings[allow_remember_for_days]',- configuration[:allow_remember_for_days],+ configuration['allow_remember_for_days'],min: '0',max: '365',step: '1',diff --git a/modules/two_factor_authentication/lib/open_project/two_factor_authentication/engine.rb b/modules/two_factor_authentication/lib/open_project/two_factor_authentication/engine.rbindex 6ff56c086d4..9ce9143fc65 100644--- a/modules/two_factor_authentication/lib/open_project/two_factor_authentication/engine.rb+++ b/modules/two_factor_authentication/lib/open_project/two_factor_authentication/engine.rb@@ -17,7 +17,8 @@ module OpenProject::TwoFactorAuthenticationenforced: false,# Don't allow remember cookieallow_remember_for_days: 0- }+ },+ env_alias: '2FA' # can override values with OPENPROJECT_2FA env var},bundled: true domenu :my_menu,diff --git a/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy/base.rb b/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy/base.rbindex 51e0dbb0cc4..615438bb00e 100644--- a/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy/base.rb+++ b/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy/base.rb@@ -73,7 +73,7 @@ module OpenProject::TwoFactorAuthenticationenddef self.configuration_params- OpenProject::Configuration['2fa'][identifier]+ Setting.plugin_openproject_two_factor_authentication[identifier.to_s]endprotecteddiff --git a/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy/message_bird.rb b/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy/message_bird.rbindex 8d615cbfd31..9dcee979a34 100644--- a/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy/message_bird.rb+++ b/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy/message_bird.rb@@ -63,7 +63,7 @@ module OpenProject::TwoFactorAuthenticationenddef message_bird_client- ::MessageBird::Client.new(configuration_params[:apikey])+ ::MessageBird::Client.new(configuration_params['apikey'])end##diff --git a/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy/restdt.rb b/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy/restdt.rbindex 8de71330037..5dcf1c28240 100644--- a/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy/restdt.rb+++ b/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy/restdt.rb@@ -27,10 +27,10 @@ module OpenProject::TwoFactorAuthenticationdef service_params{- url: URI(configuration_params[:service_url]),+ url: URI(configuration_params['service_url']),request_base: {- user: configuration_params[:username],- pass: configuration_params[:password],+ user: configuration_params['username'],+ pass: configuration_params['password'],# The API supports XML and plain.# In the latter case, only the status code is returned.output: 'plain'diff --git a/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy/sns.rb b/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy/sns.rbindex 96a01a360cf..4f90c18ed6b 100644--- a/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy/sns.rb+++ b/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy/sns.rb@@ -23,6 +23,14 @@ module OpenProject::TwoFactorAuthentication[:sms]end+ def self.validate_params+ %w[access_key_id secret_access_key region].each do |key|+ unless configuration_params[key]+ raise ArgumentError, "Amazon SNS delivery settings is missing mandatory key :#{key}"+ end+ end+ end+privatedef send_sms@@ -54,8 +62,9 @@ module OpenProject::TwoFactorAuthenticationphoneend+ # rubocop:disable Metric/AbcSizedef submit- aws_params = configuration_params.slice :region, :access_key_id, :secret_access_key+ aws_params = configuration_params.slice 'region', 'access_key_id', 'secret_access_key'sns = ::Aws::SNS::Client.new aws_paramssns.set_sms_attributes(@@ -65,7 +74,7 @@ module OpenProject::TwoFactorAuthentication'DefaultSMSType' => 'Transactional',# Set sender ID name (may not be supported in all countries)- 'DefaultSenderID' => configuration_params.fetch(:sender_id, 'OpenProject')+ 'DefaultSenderID' => configuration_params.fetch('sender_id', 'OpenProject')})@@ -82,20 +91,12 @@ module OpenProject::TwoFactorAuthenticationraise resultrescue StandardError => eRails.logger.error do- "[2FA] SNS delivery failed for user #{user.login} " \- "(Error: #{e})"+ "[2FA] SNS delivery failed for user #{user.login} (Error: #{e})"endraise I18n.t('two_factor_authentication.sns.delivery_failed')end-- def self.validate_params- %i(access_key_id secret_access_key region).each do |key|- unless configuration_params[key]- raise ArgumentError, "Amazon SNS delivery settings is missing mandatory key :#{key}"- end- end- end+ # rubocop:enable Metric/AbcSizeendendenddiff --git a/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy_manager.rb b/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy_manager.rbindex 7217c3f9a93..461406cf6d5 100644--- a/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy_manager.rb+++ b/modules/two_factor_authentication/lib/open_project/two_factor_authentication/token_strategy_manager.rb@@ -25,7 +25,7 @@ module OpenProject::TwoFactorAuthenticationt = strategy.device_typeif types.key? traise ArgumentError, "Type #{t} already registered with strategy #{types[t].identifier}. " \- "You cannot register two strategies with the same types."+ "You cannot register two strategies with the same types."endtypes[t] = strategy@@ -45,23 +45,23 @@ module OpenProject::TwoFactorAuthentication### Determines whether admins can register devices on user's behalfdef admin_register_sms_strategy- enabled? && active_strategies.detect { |strategy_class| strategy_class.mobile_token? }+ enabled? && active_strategies.detect(&:mobile_token?)end### Whether the system requires 2FA for all usersdef enforced?- !!configuration[:enforced]+ !!configuration['enforced']end### Determine whether the plugin settings can be changed from the UIdef configurable_by_ui?- !configuration[:hide_settings_menu_item]+ !configuration['hide_settings_menu_item']enddef allow_remember_for_days- configuration[:allow_remember_for_days].to_i+ configuration['allow_remember_for_days'].to_iend##@@ -73,10 +73,10 @@ module OpenProject::TwoFactorAuthentication### Fetch all active strategiesdef active_strategies- configuration.fetch(:active_strategies, [])- .map(&:to_s)- .uniq- .map { |strategy| lookup_active_strategy strategy }+ configuration.fetch('active_strategies', [])+ .map(&:to_s)+ .uniq+ .map { |strategy| lookup_active_strategy strategy }end##@@ -93,40 +93,32 @@ module OpenProject::TwoFactorAuthenticationtypes << s.device_typeend- classes = types.map { |type| [type, ::TwoFactorAuthentication::Device.const_get(type.to_s.camelize)] }- Hash[classes]+ classes = types.to_h { |type| [type, ::TwoFactorAuthentication::Device.const_get(type.to_s.camelize)] }end### 2FA Plugin configurationdef configuration- config = OpenProject::Configuration['2fa'] || {}- settings = Setting.plugin_openproject_two_factor_authentication || {}+ config = Setting.plugin_openproject_two_factor_authentication || {}- merge_with_settings! config, settings+ merge_with_settings! configconfigenddef enforced_by_configuration?- enforced = (OpenProject::Configuration['2fa'] || {})[:enforced]+ enforced = (OpenProject::Configuration['2fa'] || {})['enforced']ActiveModel::Type::Boolean.new.cast enforcedend- def merge_with_settings!(config, settings)- predefined_strategies = config.fetch(:active_strategies, [])- additional_strategies = settings.fetch(:active_strategies, [])-- config[:active_strategies] = predefined_strategies | additional_strategies+ def merge_with_settings!(config)+ config['active_strategies'] ||= []# Always enable totp if nothing is enabled- config[:active_strategies] << :totp if add_default_strategy?(config)- # Allow enforcing from settings if not true in configuration- config[:enforced] ||= settings[:enforced]- config[:allow_remember_for_days] = config.fetch(:allow_remember_for_days, settings[:allow_remember_for_days])+ config['active_strategies'] << :totp if add_default_strategy?(config)enddef add_default_strategy?(config)- config[:active_strategies].empty? && !config[:disabled].present?+ config['active_strategies'].empty? && config['disabled'].blank?enddef available_strategiesdiff --git a/modules/two_factor_authentication/spec/controllers/two_factor_authentication/authentication_controller_spec.rb b/modules/two_factor_authentication/spec/controllers/two_factor_authentication/authentication_controller_spec.rbindex 5eaa488debd..03e3147fb13 100644--- a/modules/two_factor_authentication/spec/controllers/two_factor_authentication/authentication_controller_spec.rb+++ b/modules/two_factor_authentication/spec/controllers/two_factor_authentication/authentication_controller_spec.rb@@ -13,7 +13,7 @@ describe ::TwoFactorAuthentication::AuthenticationController, with_2fa_ee: true,allow_any_instance_of(User).to receive(:any_active_memberships?).and_return(true)end- describe 'with no active strategy', with_config: { '2fa' => {} } do+ describe 'with no active strategy', with_settings: { 'plugin_openproject_two_factor_authentication' => {} } dobefore dosession[:authenticated_user_id] = user.idget :request_otp@@ -23,7 +23,7 @@ describe ::TwoFactorAuthentication::AuthenticationController, with_2fa_ee: true,enddescribe 'with no active strategy, but 2FA enforced as configuration',- with_config: { '2fa' => { active_strategies: [], enforced: true } } do+ with_settings: { 'plugin_openproject_two_factor_authentication' => { active_strategies: [], enforced: true } } dobefore doallow(OpenProject::TwoFactorAuthentication::TokenStrategyManager).to receive(:add_default_strategy?)@@ -37,7 +37,9 @@ describe ::TwoFactorAuthentication::AuthenticationController, with_2fa_ee: true,endend- describe 'with one active strategy, enforced', with_config: { '2fa' => { active_strategies: [:developer], enforced: true } } do+ describe 'with one active strategy, enforced', with_settings: {+ 'plugin_openproject_two_factor_authentication' => { active_strategies: [:developer], enforced: true }+ } docontext 'with no device' dobefore dosession[:authenticated_user_id] = user.id@@ -48,7 +50,8 @@ describe ::TwoFactorAuthentication::AuthenticationController, with_2fa_ee: true,endend- describe 'with one active strategy', with_config: { '2fa' => { active_strategies: [:developer] } } do+ describe 'with one active strategy',+ with_settings: { 'plugin_openproject_two_factor_authentication' => { active_strategies: [:developer] } } docontext 'with no device' dobefore dosession[:authenticated_user_id] = user.id@@ -73,23 +76,28 @@ describe ::TwoFactorAuthentication::AuthenticationController, with_2fa_ee: true,context 'with an invalid device' dolet!(:device) { create :two_factor_authentication_device_totp, user: user, channel: :totp }+it_behaves_like '2FA login request failure', I18n.t('two_factor_authentication.error_no_matching_strategy')endcontext 'with an active device' dolet!(:device) { create :two_factor_authentication_device_sms, user: user, channel: :sms }+it_behaves_like '2FA SMS request success'endend- describe 'with two active strategy', with_config: { '2fa' => { active_strategies: %i[developer totp] } } do+ describe 'with two active strategy',+ with_settings: { 'plugin_openproject_two_factor_authentication' => { active_strategies: %i[developer totp] } } docontext 'with a totp device' dolet!(:device) { create :two_factor_authentication_device_totp, user: user, channel: :totp }+it_behaves_like '2FA TOTP request success'endcontext 'with an sms device' dolet!(:device) { create :two_factor_authentication_device_sms, user: user, channel: :sms }+it_behaves_like '2FA SMS request success'endend@@ -99,7 +107,7 @@ describe ::TwoFactorAuthentication::AuthenticationController, with_2fa_ee: true,get :confirm_otpend- it "should receive a 405" do+ it "receives a 405" doexpect(response.response_code).to eq(405)endenddiff --git a/modules/two_factor_authentication/spec/controllers/two_factor_authentication/forced_registration/two_factor_devices_controller_spec.rb b/modules/two_factor_authentication/spec/controllers/two_factor_authentication/forced_registration/two_factor_devices_controller_spec.rbindex 346d0d901c2..51d297addbd 100644--- a/modules/two_factor_authentication/spec/controllers/two_factor_authentication/forced_registration/two_factor_devices_controller_spec.rb+++ b/modules/two_factor_authentication/spec/controllers/two_factor_authentication/forced_registration/two_factor_devices_controller_spec.rb@@ -5,21 +5,26 @@ describe ::TwoFactorAuthentication::ForcedRegistration::TwoFactorDevicesControlllet(:user) { create(:user, login: 'foobar') }let(:logged_in_user) { User.anonymous }let(:active_strategies) { [] }- let(:config) { {} }let(:authenticated_user_id) { user.id }let(:user_force_2fa) { true }+ include_context 'with settings' do+ let(:settings) do+ {+ plugin_openproject_two_factor_authentication: {+ 'active_strategies' => active_strategies+ }+ }+ end+ end+before doallow(User).to receive(:current).and_return(User.anonymous)session[:authenticated_user_id] = authenticated_user_idsession[:authenticated_user_force_2fa] = user_force_2fasession[:stage_secrets] = { two_factor_authentication: 'asdf' }- allow(OpenProject::Configuration).to receive(:[]).and_call_original- allow(OpenProject::Configuration)- .to receive(:[]).with('2fa')- .and_return({ active_strategies: active_strategies }.merge(config).with_indifferent_access)allow(OpenProject::TwoFactorAuthentication::TokenStrategyManager).to receive(:add_default_strategy?).and_return false@@ -41,17 +46,6 @@ describe ::TwoFactorAuthentication::ForcedRegistration::TwoFactorDevicesControllendend- context 'when authenticated_user present, but no registration' do- let(:active_strategies) { [:developer] }- let(:authenticated_user_id) { nil }- let(:user_force_2fa) { nil }-- it 'does not give access' do- expect(response).to be_redirect- expect(response).to redirect_to stage_failure_path(stage: :two_factor_authentication)- end- end-context 'when logged in, but not enabled' doit 'does not give access' doexpect(response.status).to eq 404diff --git a/modules/two_factor_authentication/spec/controllers/two_factor_authentication/my/two_factor_devices_controller_spec.rb b/modules/two_factor_authentication/spec/controllers/two_factor_authentication/my/two_factor_devices_controller_spec.rbindex eefe28a0c5e..7d7d480576a 100644--- a/modules/two_factor_authentication/spec/controllers/two_factor_authentication/my/two_factor_devices_controller_spec.rb+++ b/modules/two_factor_authentication/spec/controllers/two_factor_authentication/my/two_factor_devices_controller_spec.rb@@ -8,12 +8,18 @@ describe ::TwoFactorAuthentication::My::TwoFactorDevicesController, with_2fa_ee:let(:active_strategies) { [] }let(:config) { {} }+ include_context 'with settings' do+ let(:settings) do+ {+ plugin_openproject_two_factor_authentication: {+ 'active_strategies' => active_strategies+ }.merge(config)+ }+ end+ end+before doallow(User).to receive(:current).and_return(logged_in_user)- allow(OpenProject::Configuration).to receive(:[]).and_call_original- allow(OpenProject::Configuration)- .to receive(:[]).with('2fa')- .and_return({ active_strategies: active_strategies }.merge(config).with_indifferent_access)allow(OpenProject::TwoFactorAuthentication::TokenStrategyManager).to receive(:add_default_strategy?).and_return falsediff --git a/modules/two_factor_authentication/spec/controllers/two_factor_authentication/users/two_factor_devices_controller_spec.rb b/modules/two_factor_authentication/spec/controllers/two_factor_authentication/users/two_factor_devices_controller_spec.rbindex 4a40a735865..dc545536b8f 100644--- a/modules/two_factor_authentication/spec/controllers/two_factor_authentication/users/two_factor_devices_controller_spec.rb+++ b/modules/two_factor_authentication/spec/controllers/two_factor_authentication/users/two_factor_devices_controller_spec.rb@@ -9,12 +9,18 @@ describe ::TwoFactorAuthentication::Users::TwoFactorDevicesController, with_2fa_let(:active_strategies) { [:developer] }let(:config) { {} }+ include_context 'with settings' do+ let(:settings) do+ {+ plugin_openproject_two_factor_authentication: {+ 'active_strategies' => active_strategies+ }.merge(config)+ }+ end+ end+before doallow(User).to receive(:current).and_return(logged_in_user)- allow(OpenProject::Configuration).to receive(:[]).and_call_original- allow(OpenProject::Configuration)- .to receive(:[]).with('2fa')- .and_return({ active_strategies: active_strategies }.merge(config).with_indifferent_access)allow(OpenProject::TwoFactorAuthentication::TokenStrategyManager).to receive(:add_default_strategy?).and_return falsediff --git a/modules/two_factor_authentication/spec/features/account_activation_spec.rb b/modules/two_factor_authentication/spec/features/account_activation_spec.rbindex cceb6f28d43..3bd7415996b 100644--- a/modules/two_factor_authentication/spec/features/account_activation_spec.rb+++ b/modules/two_factor_authentication/spec/features/account_activation_spec.rb@@ -5,7 +5,9 @@ describe 'activating an invited account',with_2fa_ee: true,type: :feature,js: true,- with_config: { '2fa': { active_strategies: [:developer] } } do+ with_settings: {+ plugin_openproject_two_factor_authentication: { 'active_strategies' => [:developer] }+ } dolet(:user) douser = build :user, first_login: trueUserInvitation.invite_user! user@@ -20,7 +22,7 @@ describe 'activating an invited account',token: token.value,only_path: true)- expect(current_path).to eql account_register_path+ expect(page).to have_current_path account_register_pathfill_in I18n.t('attributes.password'), with: 'Password1234'fill_in I18n.t('activerecord.attributes.user.password_confirmation'), with: 'Password1234'@@ -42,10 +44,12 @@ describe 'activating an invited account',it 'requests a OTP' dosms_token = nil+ # rubocop:disable RSpec/AnyInstanceallow_any_instance_of(::OpenProject::TwoFactorAuthentication::TokenStrategy::Developer).to receive(:create_mobile_otp).and_wrap_original do |m|sms_token = m.callend+ # rubocop:enable RSpec/AnyInstanceactivate!@@ -67,12 +71,18 @@ describe 'activating an invited account',fill_in I18n.t(:field_otp), with: 'asdf' # faulty tokenclick_button I18n.t(:button_login)- expect(current_path).to eql signin_path+ expect(page).to have_current_path signin_pathexpect(page).to have_content(I18n.t(:notice_account_otp_invalid))endend- context 'when enforced', with_config: { '2fa': { active_strategies: [:developer], enforced: true } } do+ context 'when enforced',+ with_settings: {+ plugin_openproject_two_factor_authentication: {+ 'active_strategies' => [:developer],+ 'enforced' => true+ }+ } dobefore doactivate!enddiff --git a/modules/two_factor_authentication/spec/features/admin_edit_two_factor_devices_spec.rb b/modules/two_factor_authentication/spec/features/admin_edit_two_factor_devices_spec.rbindex 469752848c2..bcdc9be5436 100644--- a/modules/two_factor_authentication/spec/features/admin_edit_two_factor_devices_spec.rb+++ b/modules/two_factor_authentication/spec/features/admin_edit_two_factor_devices_spec.rb@@ -1,8 +1,12 @@require_relative '../spec_helper'-describe 'Admin 2FA management', with_2fa_ee: true, type: :feature,- with_config: { '2fa': { active_strategies: %i[developer totp] } },- js: true do+describe 'Admin 2FA management',+ with_2fa_ee: true,+ type: :feature,+ with_settings: {+ plugin_openproject_two_factor_authentication: { 'active_strategies' => %i[developer totp] }+ },+ js: true dolet(:dialog) { ::Components::PasswordConfirmationDialog.new }let(:user_password) { 'admin!' * 4 }let(:other_user) { create :user, login: 'bob' }@@ -24,7 +28,7 @@ describe 'Admin 2FA management', with_2fa_ee: true, type: :feature,page.find('.admin--edit-section a').clickexpect(page).to have_selector('.generic-table--empty-row')- expect(current_path).to eq my_2fa_devices_path+ expect(page).to have_current_path my_2fa_devices_pathendit 'allows 2FA device management of the user' dodiff --git a/modules/two_factor_authentication/spec/features/backup_codes/login_with_backup_code_spec.rb b/modules/two_factor_authentication/spec/features/backup_codes/login_with_backup_code_spec.rbindex 00e9a1180f6..7b34f620d80 100644--- a/modules/two_factor_authentication/spec/features/backup_codes/login_with_backup_code_spec.rb+++ b/modules/two_factor_authentication/spec/features/backup_codes/login_with_backup_code_spec.rb@@ -2,7 +2,9 @@ require_relative '../../spec_helper'require_relative '../shared_2fa_examples'describe 'Login with 2FA backup code', with_2fa_ee: true, type: :feature,- with_config: { '2fa': { active_strategies: [:developer] } },+ with_settings: {+ plugin_openproject_two_factor_authentication: { 'active_strategies' => [:developer] }+ },js: true dolet(:user_password) { 'bob!' * 4 }let(:user) do@@ -13,7 +15,7 @@ describe 'Login with 2FA backup code', with_2fa_ee: true, type: :feature,endlet!(:device) { create :two_factor_authentication_device_sms, user: user, active: true, default: true }- context 'user has no backup code' do+ context 'when user has no backup code' doit 'does not show the backup code link' dofirst_login_step@@ -23,7 +25,7 @@ describe 'Login with 2FA backup code', with_2fa_ee: true, type: :feature,endend- context 'user has backup codes' do+ context 'when user has backup codes' dolet!(:valid_backup_codes) { ::TwoFactorAuthentication::BackupCode.regenerate! user }it 'allows entering a backup code' do@@ -51,7 +53,7 @@ describe 'Login with 2FA backup code', with_2fa_ee: true, type: :feature,# Expect failureexpect(page).to have_selector('.flash.error', text: I18n.t('two_factor_authentication.error_invalid_backup_code'))- expect(current_path).to eql signin_path+ expect(page).to have_current_path signin_path# Try again!first_login_stepdiff --git a/modules/two_factor_authentication/spec/features/login/login_enforced_2fa_spec.rb b/modules/two_factor_authentication/spec/features/login/login_enforced_2fa_spec.rbindex 3d8f18db788..d6361f22dee 100644--- a/modules/two_factor_authentication/spec/features/login/login_enforced_2fa_spec.rb+++ b/modules/two_factor_authentication/spec/features/login/login_enforced_2fa_spec.rb@@ -1,9 +1,16 @@require_relative '../../spec_helper'require_relative '../shared_2fa_examples'-describe 'Login with enforced 2FA', with_2fa_ee: true, type: :feature,- with_config: { '2fa': { active_strategies: [:developer], enforced: true } },- js: true do+describe 'Login with enforced 2FA',+ with_2fa_ee: true,+ type: :feature,+ with_settings: {+ plugin_openproject_two_factor_authentication: {+ 'active_strategies' => [:developer],+ 'enforced' => true+ }+ },+ js: true dolet(:user_password) { 'bob!' * 4 }let(:user) docreate(:user,@@ -17,10 +24,12 @@ describe 'Login with enforced 2FA', with_2fa_ee: true, type: :feature,it 'requests a 2FA' dosms_token = nil+ # rubocop:disable RSpec/AnyInstanceallow_any_instance_of(::OpenProject::TwoFactorAuthentication::TokenStrategy::Developer)- .to receive(:create_mobile_otp).and_wrap_original do |m|+ .to receive(:create_mobile_otp).and_wrap_original do |m|sms_token = m.callend+ # rubocop:enable RSpec/AnyInstancefirst_login_steptwo_factor_step(sms_token)@@ -32,7 +41,7 @@ describe 'Login with enforced 2FA', with_2fa_ee: true, type: :feature,two_factor_step('whatever')expect(page).to have_selector('.flash.error', text: I18n.t(:notice_account_otp_invalid))- expect(current_path).to eql signin_path+ expect(page).to have_current_path signin_pathendenddiff --git a/modules/two_factor_authentication/spec/features/login/login_with_2fa_spec.rb b/modules/two_factor_authentication/spec/features/login/login_with_2fa_spec.rbindex 5ab2f2f2be4..476e3677bdf 100644--- a/modules/two_factor_authentication/spec/features/login/login_with_2fa_spec.rb+++ b/modules/two_factor_authentication/spec/features/login/login_with_2fa_spec.rb@@ -1,9 +1,15 @@require_relative '../../spec_helper'require_relative '../shared_2fa_examples'-describe 'Login with 2FA device', with_2fa_ee: true, type: :feature,- with_config: { '2fa': { active_strategies: [:developer] } },- js: true do+describe 'Login with 2FA device',+ with_2fa_ee: true,+ type: :feature,+ with_settings: {+ plugin_openproject_two_factor_authentication: {+ 'active_strategies' => [:developer]+ }+ },+ js: true dolet(:user_password) { 'bob!' * 4 }let(:user) docreate(:user,@@ -17,10 +23,12 @@ describe 'Login with 2FA device', with_2fa_ee: true, type: :feature,it 'requests a 2FA' dosms_token = nil+ # rubocop:disable RSpec/AnyInstanceallow_any_instance_of(::OpenProject::TwoFactorAuthentication::TokenStrategy::Developer)- .to receive(:create_mobile_otp).and_wrap_original do |m|+ .to receive(:create_mobile_otp).and_wrap_original do |m|sms_token = m.callend+ # rubocop:enable RSpec/AnyInstancefirst_login_steptwo_factor_step(sms_token)@@ -32,7 +40,7 @@ describe 'Login with 2FA device', with_2fa_ee: true, type: :feature,two_factor_step('whatever')expect(page).to have_selector('.flash.error', text: I18n.t(:notice_account_otp_invalid))- expect(current_path).to eql signin_path+ expect(page).to have_current_path signin_pathendendenddiff --git a/modules/two_factor_authentication/spec/features/login/switch_available_devices_spec.rb b/modules/two_factor_authentication/spec/features/login/switch_available_devices_spec.rbindex 27ad878d3a1..bd1a6dd99de 100644--- a/modules/two_factor_authentication/spec/features/login/switch_available_devices_spec.rb+++ b/modules/two_factor_authentication/spec/features/login/switch_available_devices_spec.rb@@ -1,9 +1,13 @@require_relative '../../spec_helper'require_relative '../shared_2fa_examples'-describe 'Login by switching 2FA device', with_2fa_ee: true, type: :feature,- with_config: { '2fa': { active_strategies: %i[developer totp] } },- js: true do+describe 'Login by switching 2FA device',+ with_2fa_ee: true,+ type: :feature,+ with_settings: {+ plugin_openproject_two_factor_authentication: { 'active_strategies' => %i[developer totp] }+ },+ js: true dolet(:user_password) { 'bob!' * 4 }let(:user) docreate(:user,diff --git a/modules/two_factor_authentication/spec/features/my_two_factor_devices_spec.rb b/modules/two_factor_authentication/spec/features/my_two_factor_devices_spec.rbindex 3eb0f28ab04..aadd2d78ed1 100644--- a/modules/two_factor_authentication/spec/features/my_two_factor_devices_spec.rb+++ b/modules/two_factor_authentication/spec/features/my_two_factor_devices_spec.rb@@ -1,9 +1,12 @@require_relative '../spec_helper'-describe 'My Account 2FA configuration', with_2fa_ee: true,- type: :feature,- with_config: { '2fa': { active_strategies: %i[developer totp] } },- js: true do+describe 'My Account 2FA configuration',+ with_2fa_ee: true,+ type: :feature,+ with_settings: {+ plugin_openproject_two_factor_authentication: { 'active_strategies' => %i[developer totp] }+ },+ js: true dolet(:dialog) { ::Components::PasswordConfirmationDialog.new }let(:user_password) { 'boB!4' * 4 }let(:user) do@@ -26,7 +29,7 @@ describe 'My Account 2FA configuration', with_2fa_ee: true,# Visit inline createfind('.wp-inline-create--add-link').clickexpect(page).to have_selector('h2', text: I18n.t('two_factor_authentication.devices.add_new'))- expect(current_path).to eq new_my_2fa_device_path+ expect(page).to have_current_path new_my_2fa_device_path# Select SMSfind('.mobile-otp-new-device-sms .button').click@@ -45,10 +48,12 @@ describe 'My Account 2FA configuration', with_2fa_ee: true,# Log token for next accesssms_token = nil+ # rubocop:disable RSpec/AnyInstanceallow_any_instance_of(::OpenProject::TwoFactorAuthentication::TokenStrategy::Developer)- .to receive(:create_mobile_otp).and_wrap_original do |m|+ .to receive(:create_mobile_otp).and_wrap_original do |m|sms_token = m.callend+ # rubocop:enable RSpec/AnyInstanceclick_button I18n.t(:button_continue)diff --git a/modules/two_factor_authentication/spec/features/password_change_spec.rb b/modules/two_factor_authentication/spec/features/password_change_spec.rbindex 5618a9be115..98a8834f67e 100644--- a/modules/two_factor_authentication/spec/features/password_change_spec.rb+++ b/modules/two_factor_authentication/spec/features/password_change_spec.rb@@ -1,8 +1,14 @@require_relative '../spec_helper'-describe 'Password change with OTP', with_2fa_ee: true, type: :feature,- with_config: { '2fa': { active_strategies: [:developer] } },- js: true do+describe 'Password change with OTP',+ with_2fa_ee: true,+ type: :feature,+ with_settings: {+ plugin_openproject_two_factor_authentication: {+ 'active_strategies' => [:developer]+ }+ },+ js: true dolet(:user_password) { 'boB&' * 4 }let(:new_user_password) { '%obB' * 4 }let(:user) do@@ -22,10 +28,12 @@ describe 'Password change with OTP', with_2fa_ee: true, type: :feature,endsms_token = nil+ # rubocop:disable RSpec/AnyInstanceallow_any_instance_of(::OpenProject::TwoFactorAuthentication::TokenStrategy::Developer)- .to receive(:create_mobile_otp).and_wrap_original do |m|+ .to receive(:create_mobile_otp).and_wrap_original do |m|sms_token = m.callend+ # rubocop:enable RSpec/AnyInstanceexpect(page).to have_selector('h2', text: I18n.t(:button_change_password))within('#content') do@@ -43,7 +51,7 @@ describe 'Password change with OTP', with_2fa_ee: true, type: :feature,click_button I18n.t(:button_login)end- expect(current_path).to eql expected_path_after_login+ expect(page).to have_current_path(expected_path_after_login, ignore_query: true)endcontext 'when password is expired',diff --git a/modules/two_factor_authentication/spec/features/remember_cookie/login_with_remember_cookie_spec.rb b/modules/two_factor_authentication/spec/features/remember_cookie/login_with_remember_cookie_spec.rbindex 685945163d9..7f4d531ae8c 100644--- a/modules/two_factor_authentication/spec/features/remember_cookie/login_with_remember_cookie_spec.rb+++ b/modules/two_factor_authentication/spec/features/remember_cookie/login_with_remember_cookie_spec.rb@@ -4,7 +4,12 @@ require_relative '../shared_2fa_examples'describe 'Login with 2FA remember cookie',type: :feature,with_2fa_ee: true,- with_config: { '2fa': { active_strategies: [:developer], allow_remember_for_days: 30 } },+ with_settings: {+ plugin_openproject_two_factor_authentication: {+ active_strategies: [:developer],+ allow_remember_for_days: 30+ }+ },js: true dolet(:user_password) do"user!user!"@@ -40,15 +45,20 @@ describe 'Login with 2FA remember cookie',expect_not_logged_inend- context 'not enabled',- with_config: { '2fa': { active_strategies: [:developer], allow_remember_for_days: 0 } } do+ context 'when not enabled',+ with_settings: {+ plugin_openproject_two_factor_authentication: {+ active_strategies: [:developer],+ allow_remember_for_days: 0+ }+ } doit 'does not show the save form' dofirst_login_stepexpect(page).to have_no_selector('input#remember_me')endend- context 'user has no remember cookie' do+ context 'when user has no remember cookie' doit 'can remove the autologin cookie after login' dologin_with_cookievisit my_2fa_devices_pathdiff --git a/modules/two_factor_authentication/spec/lib/token_strategy_manager_spec.rb b/modules/two_factor_authentication/spec/lib/token_strategy_manager_spec.rbindex 8b2d17f55aa..a45f6ce9090 100644--- a/modules/two_factor_authentication/spec/lib/token_strategy_manager_spec.rb+++ b/modules/two_factor_authentication/spec/lib/token_strategy_manager_spec.rb@@ -1,5 +1,6 @@require_relative '../spec_helper'+# rubocop:disable RSpec/NestedGroupsdescribe ::OpenProject::TwoFactorAuthentication::TokenStrategyManager dolet(:dev_strategy) { ::OpenProject::TwoFactorAuthentication::TokenStrategy::Developer }let(:totp_strategy) { ::OpenProject::TwoFactorAuthentication::TokenStrategy::Totp }@@ -12,10 +13,14 @@ describe ::OpenProject::TwoFactorAuthentication::TokenStrategyManager dolet(:enforced) { false }context 'without EE' do- before do- allow(OpenProject::Configuration)- .to receive(:[]).with('2fa')- .and_return(active_strategies: [:developer])+ include_context 'with settings' do+ let(:settings) do+ {+ plugin_openproject_two_factor_authentication: {+ 'active_strategies' => %i[developer]+ }+ }+ endendit 'is not enabled' do@@ -24,10 +29,12 @@ describe ::OpenProject::TwoFactorAuthentication::TokenStrategyManager doendcontext 'with EE', with_2fa_ee: true do- before do- allow(OpenProject::Configuration)- .to receive(:[]).with('2fa')- .and_return(configuration)+ include_context 'with settings' do+ let(:settings) do+ {+ plugin_openproject_two_factor_authentication: configuration+ }+ endenddescribe '#find_matching_strategy' do@@ -35,6 +42,7 @@ describe ::OpenProject::TwoFactorAuthentication::TokenStrategyManager docontext 'when no strategy is set' dolet(:active_strategies) { [] }+it 'returns nil' doexpect(subject).to be_nilend@@ -52,7 +60,7 @@ describe ::OpenProject::TwoFactorAuthentication::TokenStrategyManager dolet(:active_strategies) { [:totp] }it 'returns the strategy' do- expect(subject).to eq(nil)+ expect(subject).to be_nilendendend@@ -71,64 +79,19 @@ describe ::OpenProject::TwoFactorAuthentication::TokenStrategyManager doendend- describe 'with additional settings given' do- let(:active_strategies) { [:developer] }- let(:enforced) { false }-- before do- allow(Setting).to receive(:plugin_openproject_two_factor_authentication).and_return(settings)- end-- context 'when nothing given' do- let(:settings) { nil }-- it 'uses the configuration' do- expect(described_class.active_strategies).to eq([dev_strategy])- expect(described_class).not_to be_enforced- end- end-- context 'when additional strategy given' do- let(:settings) { { active_strategies: [:totp] } }-- it 'merges configuration and settings' do- expect(described_class.active_strategies).to eq([dev_strategy, totp_strategy])- expect(described_class).not_to be_enforced- end- end-- context 'when enforced set' do- context 'when true and config is false' do- let(:enforced) { false }- let(:settings) { { enforced: true } }-- it 'does override the configuration' do- expect(described_class).to be_enforced- end- end-- context 'when false and config is true' do- let(:enforced) { true }- let(:settings) { { enforced: false } }-- it 'does not override the configuration' do- expect(described_class).to be_enforced- end- end- end- end-describe '#validate_active_strategies!' dosubject { described_class.validate_active_strategies! }+context 'when no strategy is set' dolet(:active_strategies) { [] }+before doallow(OpenProject::TwoFactorAuthentication::TokenStrategyManager).to receive(:add_default_strategy?)- .and_return false+ .and_return falseend- context 'and enforced is false' do+ context 'when enforced is false' dolet(:enforced) { false }it 'accepts that' do@@ -138,7 +101,7 @@ describe ::OpenProject::TwoFactorAuthentication::TokenStrategyManager doendend- context 'and enforced is true' do+ context 'when enforced is true' dolet(:enforced) { true }it 'raises and error that a strategy is needed' do@@ -152,7 +115,7 @@ describe ::OpenProject::TwoFactorAuthentication::TokenStrategyManager docontext 'when a strategy is set' dolet(:active_strategies) { [:developer] }- context 'and it is valid' do+ context 'when it is valid' doit 'returns that' doexpect { subject }.not_to raise_errorexpect(described_class.active_strategies).to eq([dev_strategy])@@ -161,11 +124,10 @@ describe ::OpenProject::TwoFactorAuthentication::TokenStrategyManager doendend- context 'and it is invalid' do- before do- expect(dev_strategy).to receive(:validate!).and_raise 'Error!'- end+ context 'when it is invalid' doit 'raises' do+ allow(dev_strategy).to receive(:validate!).and_raise 'Error!'+expect { subject }.to raise_error 'Error!'expect(described_class).to be_enabledexpect(described_class).not_to be_enforced@@ -175,3 +137,4 @@ describe ::OpenProject::TwoFactorAuthentication::TokenStrategyManager doendendend+# rubocop:enable RSpec/NestedGroupsdiff --git a/modules/two_factor_authentication/spec/models/devices/totp_spec.rb b/modules/two_factor_authentication/spec/models/devices/totp_spec.rbindex 0f60122d00f..89edc5f2605 100644--- a/modules/two_factor_authentication/spec/models/devices/totp_spec.rb+++ b/modules/two_factor_authentication/spec/models/devices/totp_spec.rb@@ -4,6 +4,7 @@ require 'timecop'describe ::TwoFactorAuthentication::Device::Totp, with_2fa_ee: true, type: :model dolet(:user) { create :user }let(:channel) { :totp }+subject { described_class.new identifier: 'foo', channel: channel, user: user, active: true }describe 'validations' do@@ -27,40 +28,47 @@ describe ::TwoFactorAuthentication::Device::Totp, with_2fa_ee: true, type: :modedescribe 'token validation' dolet(:totp) { subject.send :totp }- context 'drift', with_config: { '2fa': { otp_drift_window: 30 } } do+ context 'when setting drift',+ with_settings: {+ plugin_openproject_two_factor_authentication: {+ 'otp_drift_window' => 30+ }+ } doit 'uses the drift window from configuration' doexpect(subject.allowed_drift).to eq 30endend- context 'no drift set' do+ context 'when no drift set' doit 'uses the default drift window' doexpect(subject.allowed_drift).to eq 60endit 'uses the drift value for verification' do# Assume never used+ # rubocop:disable RSpec/SubjectStuballow(subject).to receive(:last_used_at).and_return nilallow(subject).to receive(:update_column).with(:last_used_at, any_args)+ # rubocop:enable RSpec/SubjectStub- Timecop.freeze(Time.now) do- old_valid = totp.at(Time.now - 30.seconds)- old_valid2 = totp.at(Time.now - 60.seconds)- new_valid = totp.at(Time.now + 30.seconds)- new_valid2 = totp.at(Time.now + 60.seconds)+ Timecop.freeze(Time.current) do+ old_valid = totp.at(30.seconds.ago)+ old_valid2 = totp.at(60.seconds.ago)+ new_valid = totp.at(30.seconds.from_now)+ new_valid2 = totp.at(60.seconds.from_now)# Next iteration at interval is 90# which should be invalid- old_invalid = totp.at(Time.now - 90.seconds)- new_invalid = totp.at(Time.now + 90.seconds)+ old_invalid = totp.at(90.seconds.ago)+ new_invalid = totp.at(90.seconds.from_now)- expect(subject.verify_token(old_valid)).to eq true- expect(subject.verify_token(old_valid2)).to eq true- expect(subject.verify_token(new_valid)).to eq true- expect(subject.verify_token(new_valid2)).to eq true+ expect(subject.verify_token(old_valid)).to be true+ expect(subject.verify_token(old_valid2)).to be true+ expect(subject.verify_token(new_valid)).to be true+ expect(subject.verify_token(new_valid2)).to be true- expect(subject.verify_token(old_invalid)).to eq false- expect(subject.verify_token(new_invalid)).to eq false+ expect(subject.verify_token(old_invalid)).to be false+ expect(subject.verify_token(new_invalid)).to be falseendendend@@ -68,18 +76,18 @@ describe ::TwoFactorAuthentication::Device::Totp, with_2fa_ee: true, type: :modeit 'avoids double verification' dosubject.save!- valid = totp.at(Time.now)- expect(subject.verify_token(valid)).to eq true+ valid = totp.at(Time.current)+ expect(subject.verify_token(valid)).to be truelast_date = subject.last_used_atexpect(last_date).to be_present- expect(subject.verify_token(valid)).to eq false+ expect(subject.verify_token(valid)).to be false- future = Time.now + 1.minute+ future = Time.current + 1.minuteTimecop.freeze(future) dovalid = totp.now- expect(subject.verify_token(valid)).to eq true- expect(subject.verify_token(valid)).to eq false+ expect(subject.verify_token(valid)).to be true+ expect(subject.verify_token(valid)).to be falseendendenddiff --git a/modules/two_factor_authentication/spec/services/token_delivery/message_bird_spec.rb b/modules/two_factor_authentication/spec/services/token_delivery/message_bird_spec.rbindex 45b9196e2d3..9c0f4e764ee 100644--- a/modules/two_factor_authentication/spec/services/token_delivery/message_bird_spec.rb+++ b/modules/two_factor_authentication/spec/services/token_delivery/message_bird_spec.rb@@ -8,17 +8,29 @@ describe ::OpenProject::TwoFactorAuthentication::TokenStrategy::MessageBird, witlet!(:device) { create :two_factor_authentication_device_sms, user: user, channel: channel }let(:service_url) { 'https://example.org/foobar' }+ let(:apikey) { 'whatever' }let(:params) do{- apikey: 'whatever'+ apikey: apikey}end- before do- allow(OpenProject::Configuration)- .to receive(:[]).with('2fa')- .and_return(active_strategies: [:message_bird], message_bird: params)+ let(:result) { subject.request }+ subject { ::TwoFactorAuthentication::TokenService.new user: user }++ include_context 'with settings' do+ let(:settings) do+ {+ plugin_openproject_two_factor_authentication: {+ 'active_strategies' => [:message_bird],+ 'message_bird' => params+ }+ }+ end+ end++ before doallow_any_instance_of(::OpenProject::TwoFactorAuthentication::TokenStrategy::MessageBird).to receive(:create_mobile_otp).and_return('1234')@@ -34,12 +46,21 @@ describe ::OpenProject::TwoFactorAuthentication::TokenStrategy::MessageBird, witendend- subject { ::TwoFactorAuthentication::TokenService.new user: user }- let(:result) { subject.request }+ describe 'calling a mocked test API' do+ let(:channel) { :sms }++ before do+ allow(::MessageBird::Client).to receive(:new)+ end++ it 'uses the api key defined in the settings' do+ result+ expect(::MessageBird::Client).to have_received(:new).with(apikey)+ end+ end- describe 'calling the test API' do+ describe 'calling the real test API' dolet(:apikey) { ENV['MESSAGEBIRD_TEST_APIKEY'] }- let(:params) { { apikey: apikey } }before doskip 'Missing MESSAGEBIRD_TEST_APIKEY environment variable' unless apikey.present?diff --git a/modules/two_factor_authentication/spec/services/token_delivery/restdt_spec.rb b/modules/two_factor_authentication/spec/services/token_delivery/restdt_spec.rbindex 1c29f021139..d6cdcc4c084 100644--- a/modules/two_factor_authentication/spec/services/token_delivery/restdt_spec.rb+++ b/modules/two_factor_authentication/spec/services/token_delivery/restdt_spec.rb@@ -25,11 +25,22 @@ describe ::OpenProject::TwoFactorAuthentication::TokenStrategy::Restdt, with_2fa}end- before do- allow(OpenProject::Configuration)- .to receive(:[]).with('2fa')- .and_return(active_strategies: [:restdt], restdt: params)+ let(:result) { subject.request }++ subject { ::TwoFactorAuthentication::TokenService.new user: user }+ include_context 'with settings' do+ let(:settings) do+ {+ plugin_openproject_two_factor_authentication: {+ 'active_strategies' => [:restdt],+ 'restdt' => params+ }+ }+ end+ end++ before doallow_any_instance_of(::OpenProject::TwoFactorAuthentication::TokenStrategy::Restdt).to receive(:create_mobile_otp).and_return('1234')@@ -45,9 +56,6 @@ describe ::OpenProject::TwoFactorAuthentication::TokenStrategy::Restdt, with_2faendend- subject { ::TwoFactorAuthentication::TokenService.new user: user }- let(:result) { subject.request }-describe 'calling a mocked API', webmock: true dolet(:response_code) { '200' }let(:channel) { :sms }@@ -74,6 +82,7 @@ describe ::OpenProject::TwoFactorAuthentication::TokenStrategy::Restdt, with_2fadescribe 'request body' docontext 'with SMS' dolet(:expected_params) { { onlycall: '0' } }+it_behaves_like 'API response', trueenddiff --git a/modules/two_factor_authentication/spec/services/token_delivery/sns_spec.rb b/modules/two_factor_authentication/spec/services/token_delivery/sns_spec.rbindex 1681942d1b5..10c039d64ef 100644--- a/modules/two_factor_authentication/spec/services/token_delivery/sns_spec.rb+++ b/modules/two_factor_authentication/spec/services/token_delivery/sns_spec.rb@@ -7,7 +7,7 @@ describe ::OpenProject::TwoFactorAuthentication::TokenStrategy::Sns, with_2fa_eelet!(:device) { create :two_factor_authentication_device_sms, user: user, channel: channel }let(:channel) { :sms }- let(:params) do+ let(:sns_params) do{region: 'eu-west-1',access_key_id: 'foobar',@@ -15,22 +15,38 @@ describe ::OpenProject::TwoFactorAuthentication::TokenStrategy::Sns, with_2fa_ee}end- before do- allow(OpenProject::Configuration)- .to receive(:[]).with('2fa')- .and_return(active_strategies: [:sns], sns: params)+ include_context 'with settings' do+ let(:settings) do+ {+ plugin_openproject_two_factor_authentication: {+ 'active_strategies' => [:sns],+ 'sns' => sns_params+ }+ }+ end+ end+ before doallow_any_instance_of(::OpenProject::TwoFactorAuthentication::TokenStrategy::Sns).to receive(:create_mobile_otp).and_return('1234')enddescribe '#setup' do- let(:params) { { region: nil } }+ context 'for valid params' do+ it 'validates without errors' do+ expect { described_class.validate! }+ .not_to raise_exception+ end+ end- it 'raises an exception for incomplete params' do- expect { described_class.validate! }- .to raise_exception(ArgumentError)+ context 'for incomplete params' do+ let(:sns_params) { { region: nil } }++ it 'raises an exception' do+ expect { described_class.validate! }+ .to raise_exception(ArgumentError)+ endendenddiff --git a/modules/two_factor_authentication/spec/services/token_service_spec.rb b/modules/two_factor_authentication/spec/services/token_service_spec.rbindex 662b50380ef..e31c59b938d 100644--- a/modules/two_factor_authentication/spec/services/token_service_spec.rb+++ b/modules/two_factor_authentication/spec/services/token_service_spec.rb@@ -6,34 +6,38 @@ describe ::TwoFactorAuthentication::TokenService, with_2fa_ee: true dolet(:dev_strategy) { ::OpenProject::TwoFactorAuthentication::TokenStrategy::Developer }let(:configuration) do{- active_strategies: active_strategies,- enforced: enforced+ 'active_strategies' => active_strategies,+ 'enforced' => enforced}endlet(:enforced) { false }- before do- allow(OpenProject::Configuration)- .to receive(:[]).with('2fa')- .and_return(configuration)- end+ let(:result) { subject.request }subject { described_class.new user: user }- let(:result) { subject.request }++ include_context 'with settings' do+ let(:settings) do+ {+ plugin_openproject_two_factor_authentication: configuration+ }+ end+ endcontext 'when no strategy is set' dolet(:active_strategies) { [] }context 'when enforced' do+ let(:enforced) { true }+before doallow(OpenProject::TwoFactorAuthentication::TokenStrategyManager).to receive(:add_default_strategy?).and_return falseend- let(:enforced) { true }it 'requires a token' do- expect(subject.requires_token?).to be_truthy+ expect(subject).to be_requires_tokenendit 'returns error when requesting' do@@ -44,6 +48,7 @@ describe ::TwoFactorAuthentication::TokenService, with_2fa_ee: true docontext 'when not enforced' dolet(:enforced) { false }+before doallow(OpenProject::TwoFactorAuthentication::TokenStrategyManager).to receive(:add_default_strategy?)@@ -51,7 +56,7 @@ describe ::TwoFactorAuthentication::TokenService, with_2fa_ee: true doendit 'requires no token' do- expect(subject.requires_token?).to be_falsey+ expect(subject).not_to be_requires_tokenendit 'returns error when requesting' do@@ -64,28 +69,28 @@ describe ::TwoFactorAuthentication::TokenService, with_2fa_ee: true docontext 'when developer strategy is set' dolet(:active_strategies) { [:developer] }- context 'but no device exists' do+ context 'when no device exists' doit 'returns an error' doexpect(result).not_to be_successexpect(result.errors.full_messages).to eq [I18n.t('two_factor_authentication.error_no_device')]endend- context 'and matching device exists' do+ context 'when matching device exists' dolet!(:device) { create :two_factor_authentication_device_sms, user: user, default: true }it 'submits the request' do- expect(subject.requires_token?).to be_truthy+ expect(subject).to be_requires_tokenexpect(result).to be_successexpect(result.errors).to be_emptyendend- context 'and non-matching device exists' do+ context 'when non-matching device exists' dolet!(:device) { create :two_factor_authentication_device_totp, user: user, default: true }it 'submits the request' do- expect(subject.requires_token?).to be_truthy+ expect(subject).to be_requires_tokenexpect(result).not_to be_successexpect(result.errors.full_messages).to eq [I18n.t('two_factor_authentication.error_no_matching_strategy')]end@@ -103,7 +108,7 @@ describe ::TwoFactorAuthentication::TokenService, with_2fa_ee: true dolet(:use_device) { nil }it 'uses the totp device' do- expect(subject.requires_token?).to be_truthy+ expect(subject).to be_requires_tokenexpect(result).to be_successexpect(result.errors).to be_empty@@ -114,8 +119,9 @@ describe ::TwoFactorAuthentication::TokenService, with_2fa_ee: true docontext 'with overridden device' dolet(:use_device) { sms_device }+it 'uses the overridden device' do- expect(subject.requires_token?).to be_truthy+ expect(subject).to be_requires_tokenexpect(result).to be_successexpect(result.errors).to be_emptydiff --git a/spec/constants/settings/definition_spec.rb b/spec/constants/settings/definition_spec.rbindex 012b62c96e4..638a3419f95 100644--- a/spec/constants/settings/definition_spec.rb+++ b/spec/constants/settings/definition_spec.rb@@ -285,6 +285,69 @@ describe Settings::Definition do})end+ it 'allows overriding configuration array from ENV with yaml/json data' do+ stub_const(+ 'ENV',+ {+ 'OPENPROJECT_BLACKLISTED_ROUTES' => '["admin/info", "admin/plugins"]'+ }+ )++ expect(value_for('blacklisted_routes'))+ .to eq(['admin/info', 'admin/plugins'])+ end++ it 'allows overriding configuration array from ENV with space separated string' do+ stub_const(+ 'ENV',+ {+ 'OPENPROJECT_BLACKLISTED_ROUTES' => 'admin/info admin/plugins'+ }+ )++ # works for OpenProject::Configuration thanks to OpenProject::Configuration::Helper mixin+ expect(OpenProject::Configuration.blacklisted_routes)+ .to eq(['admin/info', 'admin/plugins'])+ # sadly behaves differently for Setting+ expect(Setting.blacklisted_routes)+ .to eq('admin/info admin/plugins')+ end++ context 'with definitions from plugins' do+ let(:definition_2fa) { definitions_before.find { _1.name == 'plugin_openproject_two_factor_authentication' }.dup }++ before do+ # hack to have access to Setting.plugin_openproject_two_factor_authentication after+ # having done+ described_class.all << definition_2fa+ end++ # it 'allows overriding settings from ENV with aliased env name' do+ # require Rails.root.join('modules/two_factor_authentication/lib/open_project/two_factor_authentication/engine')+ # stub_const(+ # 'ENV',+ # {+ # 'OPENPROJECT_2FA' => '{"enforced": true, "allow_remember_for_days": 15}'+ # }+ # )++ # expect(value_for('plugin_openproject_two_factor_authentication'))+ # .to eq(active_strategies: [], enforced: true, allow_remember_for_days: 15)+ # end++ it 'allows overriding settings hash partially from ENV with aliased env name' do+ stub_const(+ 'ENV',+ {+ 'OPENPROJECT_2FA' => '{"enforced": true, "allow_remember_for_days": 15}'+ }+ )+ Settings::Definition.send(:override_value, definition_2fa) # override from env manually after changing ENV+ expect(value_for('plugin_openproject_two_factor_authentication'))+ .to eq({ 'active_strategies' => [], 'enforced' => true, 'allow_remember_for_days' => 15 })+ end+ end+it 'will not handle ENV vars for which no definition exists' dostub_const('ENV', { 'OPENPROJECT_BOGUS' => '1' })@@ -516,18 +579,18 @@ describe Settings::Definition doendbefore do- instance.override_value({ abc: { a: 5 }, xyz: 2 })+ instance.override_value({ abc: { 'a' => 5 }, xyz: 2 })end- it 'deep merges' do+ it 'deep merges and transforms keys to string' doexpect(instance.value).to eql({- abc: {- a: 5,- b: 2+ 'abc' => {+ 'a' => 5,+ 'b' => 2},- cde: 1,- xyz: 2+ 'cde' => 1,+ 'xyz' => 2})end@@ -664,7 +727,7 @@ describe Settings::Definition docontext 'with the minimal attributes (hash value)' dolet(:instance) dodescribed_class.new 'bogus',- value: { a: 'b' }+ value: { a: 'b', c: { d: 'e' } }endit 'has the format (in symbol) deduced' do@@ -676,6 +739,14 @@ describe Settings::Definition doexpect(instance).to be_serializedend++ it 'transforms keys to string' do+ expect(instance.value)+ .to eq({+ 'a' => 'b',+ 'c' => { 'd' => 'e' }+ })+ endendcontext 'with the minimal attributes (array value)' dodiff --git a/spec/models/setting_spec.rb b/spec/models/setting_spec.rbindex 5d940d3ae61..2d38df43781 100644--- a/spec/models/setting_spec.rb+++ b/spec/models/setting_spec.rb@@ -269,9 +269,8 @@ describe Setting, type: :model doend# tests the serialization feature to store complex data types like arrays in settings- describe 'serialized settings' do+ describe 'serialized array settings' dobefore do- # note: default_projects_modules is marked as serialized in settings.yml (no type-based automagic here)described_class.default_projects_modules = ['some_input']end@@ -279,9 +278,28 @@ describe Setting, type: :model doexpect(described_class.default_projects_modules).to eq ['some_input']expect(described_class.find_by(name: 'default_projects_modules').value).to eq ['some_input']end+ end- after do- described_class.find_by(name: 'default_projects_modules').destroy+ # tests the serialization feature to store complex data types like arrays in settings+ describe 'serialized hash settings' do+ before do+ setting = described_class.create!(name: 'repository_checkout_data')+ setting.update_columns(+ value: {+ git: { enabled: 0 },+ subversion: { enabled: 0 }+ }.to_yaml+ )+ end++ it 'deserializes hashes stored with symbol keys as string keys' do+ expected_value = {+ "git" => { "enabled" => 0 },+ "subversion" => { "enabled" => 0 }+ }++ expect(described_class.repository_checkout_data).to eq(expected_value)+ expect(described_class.find_by(name: 'repository_checkout_data').value).to eq(expected_value)endend@@ -298,7 +316,7 @@ describe Setting, type: :model doRails.cache.clearend- context 'cache is empty' do+ context 'when cache is empty' doit 'requests the settings once from database' doexpect(Setting).to receive(:pluck).with(:name, :value).oncediff --git a/spec/support/shared/with_settings.rb b/spec/support/shared/with_settings.rbindex 9595558e17e..9b131391d82 100644--- a/spec/support/shared/with_settings.rb+++ b/spec/support/shared/with_settings.rb@@ -55,7 +55,33 @@ RSpec.shared_context 'with settings reset' doendend+module WithSettingsMixin+ module_function++ def with_settings(settings)+ allow(Setting).to receive(:[]).and_call_original++ settings.each do |k, v|+ name = k.to_s.sub(/\?\Z/, '') # remove trailing question mark if present to get setting name++ raise "#{k} is not a valid setting" unless Setting.respond_to?(name)++ expect(name).not_to start_with("localized_"), -> do+ base = name[10..-1]++ "Don't use `#{name}` in `with_settings`. Do this: `with_settings: { #{base}: { \"en\" => \"#{v}\" } }`"+ end+ v = v.deep_stringify_keys if v.is_a?(Hash)++ allow(Setting).to receive(:[]).with(name).and_return v+ allow(Setting).to receive(:[]).with(name.to_sym).and_return v+ end+ end+end+RSpec.configure do |config|+ config.include WithSettingsMixin+# examples tagged with `:settings_reset` will automatically have the settings# reset before the example, and restored after.config.include_context "with settings reset", :settings_reset@@ -64,23 +90,13 @@ RSpec.configure do |config|settings = example.metadata[:with_settings]if settings.present?settings = aggregate_mocked_settings(example, settings)-- allow(Setting).to receive(:[]).and_call_original-- settings.each do |k, v|- name = k.to_s.sub(/\?\Z/, '') # remove trailing question mark if present to get setting name-- raise "#{k} is not a valid setting" unless Setting.respond_to?(name)-- expect(name).not_to start_with("localized_"), -> do- base = name[10..-1]-- "Don't use `#{name}` in `with_settings`. Do this: `with_settings: { #{base}: { \"en\" => \"#{v}\" } }`"- end-- allow(Setting).to receive(:[]).with(name).and_return v- allow(Setting).to receive(:[]).with(name.to_sym).and_return v- end+ with_settings(settings)endendend++RSpec.shared_context 'with settings' do+ before do+ with_settings(settings)+ end+end