Rails.app.credsによるマルチテナント設定
マルチテナントSaaSアプリには設定の問題があります:テナントには異なる設定が必要です。異なるAPIキー。異なる機能アクセス。異なるレート制限。
典型的な解決策は、Tenantモデルにsettings JSONカラムを追加し、コードがあちこちに散らばることです:
# これはすぐに面倒になる
api_key = current_tenant.settings.dig("stripe", "api_key") ||
Rails.application.credentials.dig(:stripe, :api_key)
Rails 8.2のCombinedConfigurationはよりクリーンなアプローチを提供します。基本をまだ見ていない場合は、まずRails.app.credsの意外な5つの使い方をご覧ください。その後、マルチテナンシーへの拡張方法を見るためにここに戻ってきてください。
テナント設定バックエンドを構築し、デフォルト値とチェーンし、Rails.app.credsを通じてすべてにアクセスします。テナントがオーバーライドを持っているかどうかに関係なく、同じコードが機能します。
アーキテクチャ
┌─────────────────────────────────────────────────────────┐
│ Rails.app.creds │
│ .option(:stripe, :api_key) │
└────────────────────────┬────────────────────────────────┘
│
┌───────────────┼───────────────┐
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Tenant │ │ ENV │ │ Credentials │
│ Settings │ │ │ │ │
│ (動的) │ │ (デプロイ) │ │ (デフォルト)│
└─────────────┘ └─────────────┘ └─────────────┘
最初の非nil値が勝つ
テナント設定はENVをオーバーライドし、ENVはcredentialsをオーバーライドします。アプリケーションコードは値がどこから来たかを知る必要も気にする必要もありません。
ステップ1:テナント設定モデル
まず、テナントに設定を保存する場所を与えます:
# db/migrate/xxx_add_settings_to_tenants.rb
class AddSettingsToTenants < ActiveRecord::Migration[8.0]
def change
add_column :tenants, :settings, :jsonb, default: {}, null: false
end
end
# app/models/tenant.rb
class Tenant < ApplicationRecord
validates :settings, json: true # JSONスキーマバリデータを使用
# 便利なメソッド
def setting(*keys)
keys.reduce(settings.deep_symbolize_keys) { |h, k| h.is_a?(Hash) ? h[k] : nil }
end
def set_setting(*keys, value)
current = settings.deep_dup
*path, final = keys
target = path.reduce(current) { |h, k| h[k.to_s] ||= {} }
target[final.to_s] = value
update!(settings: current)
end
end
ステップ2:現在のテナント
CurrentAttributesを使用して現在のテナントを追跡します:
# app/models/current.rb
class Current < ActiveSupport::CurrentAttributes
attribute :tenant
def tenant=(tenant)
super
# テナントが変更されたら設定をリロード
Rails.app.creds.reload if Rails.app.creds.respond_to?(:reload)
end
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :set_current_tenant
private
def set_current_tenant
Current.tenant = current_user&.tenant
end
end
ステップ3:テナント設定バックエンド
設定バックエンドを構築します:
# lib/tenant_configuration.rb
class TenantConfiguration
def require(*keys)
value = option(*keys)
value.nil? ? nil : value # nilを返して次のバックエンドに渡す
end
def option(*keys, default: nil)
return nil unless Current.tenant
value = Current.tenant.setting(*keys)
value.nil? ? nil : value # ここではdefaultを使わない、チェーンに任せる
end
def keys
return [] unless Current.tenant
flatten_keys(Current.tenant.settings.deep_symbolize_keys)
end
def reload
# 設定は毎回テナントから新しく読み込まれる
end
private
def flatten_keys(hash, prefix = [])
return [] unless hash.is_a?(Hash)
hash.flat_map do |k, v|
current = prefix + [k]
v.is_a?(Hash) ? flatten_keys(v, current) : [current]
end
end
end
ステップ4:接続する
# config/initializers/credentials.rb
Rails.app.creds = ActiveSupport::CombinedConfiguration.new(
TenantConfiguration.new, # テナントのオーバーライドが最初
Rails.app.envs, # 次にENV
Rails.app.credentials # 次にデフォルト
)
これで完了です。Rails.app.creds.option(:stripe, :api_key)は自動的に現在のテナントの設定を最初にチェックします。
テナント設定の使用
テナントごとに異なるAPIキー
エンタープライズテナントが独自のStripeアカウントを使用できるようにします:
# app/services/payment_service.rb
class PaymentService
def initialize
@stripe_key = Rails.app.creds.require(:stripe, :secret_key)
end
def charge(amount)
Stripe::Charge.create(
{ amount: amount, currency: "usd" },
{ api_key: @stripe_key }
)
end
end
テナントがキーを設定するための管理UI:
# app/controllers/settings/integrations_controller.rb
class Settings::IntegrationsController < ApplicationController
def update
Current.tenant.set_setting(:stripe, :secret_key, params[:stripe_secret_key])
redirect_to settings_integrations_path, notice: "Stripeを設定しました!"
end
end
テナントごとの機能フラグ
# credentials.yml.enc(デフォルト値)
features:
advanced_analytics: false
api_access: false
white_label: false
# テナント設定(プレミアムテナント用)
{
"features": {
"advanced_analytics": true,
"api_access": true
}
}
# コード内 - 以前と同じ
if Rails.app.creds.option(:features, :advanced_analytics, default: false)
render_advanced_analytics
end
プレミアムテナントは高度な分析を見ることができます。それ以外は見られません。条件ロジックは不要です。
テナントごとのレート制限
# credentials.yml.enc(デフォルト値)
limits:
api_requests_per_hour: 1000
storage_gb: 5
team_members: 10
# テナント設定(エンタープライズテナント)
{
"limits": {
"api_requests_per_hour": 50000,
"storage_gb": 500,
"team_members": -1 # 無制限
}
}
# app/services/rate_limiter.rb
class RateLimiter
def allowed?(action)
limit = Rails.app.creds.option(:limits, action, default: 100)
return true if limit == -1 # 無制限
current_count(action) < limit
end
end
管理インターフェース
テナント設定を管理するための管理パネルを構築します:
# app/controllers/admin/tenant_settings_controller.rb
class Admin::TenantSettingsController < AdminController
def show
@tenant = Tenant.find(params[:tenant_id])
@available_settings = available_settings_schema
@current_settings = @tenant.settings
end
def update
@tenant = Tenant.find(params[:tenant_id])
@tenant.update!(settings: merged_settings)
redirect_to admin_tenant_settings_path(@tenant), notice: "設定を更新しました"
end
private
def available_settings_schema
{
features: {
advanced_analytics: { type: :boolean, default: false, plans: [:pro, :enterprise] },
api_access: { type: :boolean, default: false, plans: [:enterprise] },
white_label: { type: :boolean, default: false, plans: [:enterprise] }
},
limits: {
api_requests_per_hour: { type: :integer, default: 1000, min: 100, max: 100_000 },
storage_gb: { type: :integer, default: 5, min: 1, max: 1000 },
team_members: { type: :integer, default: 10, min: 1, max: 500 }
},
integrations: {
stripe: { secret_key: { type: :secret } },
sendgrid: { api_key: { type: :secret } }
}
}
end
def merged_settings
@tenant.settings.deep_merge(settings_params.to_h)
end
end
テナント設定のキャッシュ
高トラフィックアプリでは、テナント設定をキャッシュします:
# lib/cached_tenant_configuration.rb
class CachedTenantConfiguration
CACHE_TTL = 5.minutes
def option(*keys, default: nil)
return nil unless Current.tenant
settings = cached_settings
value = keys.reduce(settings) { |h, k| h.is_a?(Hash) ? h[k] : nil }
value.nil? ? nil : value
end
def reload
return unless Current.tenant
Rails.cache.delete(cache_key)
end
private
def cached_settings
Rails.cache.fetch(cache_key, expires_in: CACHE_TTL) do
Current.tenant.settings.deep_symbolize_keys
end
end
def cache_key
"tenant_settings/#{Current.tenant.id}/#{Current.tenant.updated_at.to_i}"
end
end
キャッシュキーにはupdated_atが含まれているため、設定の変更は即座に無効化されます。
コンプライアンスのための監査ログ
エンタープライズテナントは監査ログを必要とすることが多いです。テナント設定をラップします:
# lib/audited_tenant_configuration.rb
class AuditedTenantConfiguration
def initialize(backend)
@backend = backend
end
def option(*keys, default: nil)
value = @backend.option(*keys, default: default)
log_access(keys, value, :option) if value
value
end
def require(*keys)
value = @backend.require(*keys)
log_access(keys, value, :require) if value
value
end
delegate :keys, :reload, to: :@backend
private
def log_access(keys, value, method)
TenantConfigAuditLog.create!(
tenant: Current.tenant,
keys: keys.join("."),
method: method,
accessed_at: Time.current,
user: Current.user,
request_id: Current.request_id
)
end
end
マルチテナント設定のテスト
# test/lib/tenant_configuration_test.rb
class TenantConfigurationTest < ActiveSupport::TestCase
setup do
@tenant = tenants(:acme)
@config = TenantConfiguration.new
end
test "現在のテナントがない場合はnilを返す" do
Current.tenant = nil
assert_nil @config.option(:features, :custom)
end
test "テナント設定が存在する場合はその値を返す" do
Current.tenant = @tenant
@tenant.update!(settings: { "features" => { "custom" => true } })
assert_equal true, @config.option(:features, :custom)
end
test "設定がない場合はnilを返す(次のバックエンドに渡す)" do
Current.tenant = @tenant
@tenant.update!(settings: {})
assert_nil @config.option(:features, :custom)
end
end
# test/integration/tenant_configuration_integration_test.rb
class TenantConfigurationIntegrationTest < ActionDispatch::IntegrationTest
test "テナント設定がデフォルト値をオーバーライドする" do
tenant = tenants(:acme)
tenant.update!(settings: { "features" => { "dark_mode" => true } })
sign_in users(:acme_admin)
# テナント設定
assert Rails.app.creds.option(:features, :dark_mode, default: false)
# 設定されていない値はcredentialsにフォールバック
assert_equal "default_key", Rails.app.creds.option(:api, :key, default: "default_key")
end
end
セキュリティの考慮事項
テナント入力を検証する
テナントが提供する設定を盲目的に信用しないでください:
class Tenant < ApplicationRecord
validate :settings_schema_valid
ALLOWED_SETTINGS = {
features: %i[advanced_analytics api_access white_label],
limits: %i[api_requests_per_hour storage_gb team_members],
integrations: { stripe: %i[secret_key], sendgrid: %i[api_key] }
}.freeze
private
def settings_schema_valid
settings.each_key do |key|
unless ALLOWED_SETTINGS.key?(key.to_sym)
errors.add(:settings, "無効なキーが含まれています: #{key}")
end
end
end
end
機密設定を暗号化する
APIキーとシークレットは、保存時に暗号化します:
class Tenant < ApplicationRecord
encrypts :settings # Rails 7+の暗号化
end
設定変更のレート制限
悪用を防ぎます:
class Settings::IntegrationsController < ApplicationController
before_action :rate_limit_settings_changes
private
def rate_limit_settings_changes
key = "settings_change:#{Current.tenant.id}"
if Rails.cache.read(key).to_i > 10
render json: { error: "設定変更が多すぎます" }, status: :too_many_requests
else
Rails.cache.increment(key, 1, expires_in: 1.hour)
end
end
end
完全なスタック
本番マルチテナントアプリの完全な設定チェーンは以下の通りです:
# config/initializers/credentials.rb
tenant_config = CachedTenantConfiguration.new
audited_tenant_config = AuditedTenantConfiguration.new(tenant_config)
Rails.app.creds = ActiveSupport::CombinedConfiguration.new(
audited_tenant_config, # テナント設定(キャッシュ、監査済み)
Rails.app.envs, # ENVオーバーライド(運用向け)
Rails.app.credentials # デフォルト値
)
検索順序:
- テナント設定 - この特定のテナント向けのカスタマイズ
- ENV変数 - 緊急時に運用が何でもオーバーライド可能
- 暗号化されたcredentials - 妥当なデフォルト値
アプリケーションコードはクリーンなままです:
# どのテナントでも、どの設定ソースでも動作
api_key = Rails.app.creds.require(:stripe, :secret_key)
limit = Rails.app.creds.option(:limits, :api_requests, default: 1000)
enabled = Rails.app.creds.option(:features, :new_ui, default: false)
まとめ
マルチテナント設定は、散在する条件分岐やJSONの掘り下げである必要はありません。CombinedConfigurationを使えば:
- テナントバックエンドを構築 -
Current.tenant.settingsから読み取る - 最初にチェーンする - テナント設定がデフォルト値をオーバーライドするように
- 設定に統一的にアクセス -
Rails.app.creds経由で
結果:コードの複雑さなしにテナントごとのカスタマイズ。エンタープライズテナントは独自のAPIキー、機能フラグ、制限を取得できます。コードはクリーンでテスト可能なままです。
Rails.app.credsは初めてですか?基本はRails.app.credsの意外な5つの使い方から始めてください。
CombinedConfigurationの実装についてはPR #56404をご覧ください。