使用 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 schema 验证器

  # 便捷方法
  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

租户设置密钥的管理界面:

# 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    # 默认值
)

查找顺序:

  1. 租户设置 - 此特定租户的自定义配置
  2. ENV 变量 - 运维可以在紧急情况下覆盖任何内容
  3. 加密的 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

  1. 构建租户后端Current.tenant.settings 读取
  2. 将其链接在首位 使租户设置覆盖默认值
  3. 统一访问配置 通过 Rails.app.creds

结果:无需代码复杂性即可实现租户自定义。企业租户获得自己的 API 密钥、功能开关和限制。你的代码保持简洁和可测试。

刚接触 Rails.app.creds?从 Rails.app.creds 的 5 个意想不到的用法开始了解基础。

查看 PR #56404 了解 CombinedConfiguration 的实现。