You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:解决Rails6.0下Mime::Type::InvalidMimeType异常问题

问题分析与解决方案

问题背景

使用Rails 6.0、Ruby 2.6.8环境时,order_notifications#index接口偶尔触发Mime::Type::InvalidMimeType异常,提示无效MIME类型:"{#context['com.opensymphony.xwork2.dispatcher.httpservletresponse'].addheader('37kvs3il'",同时伴随ActionView::Template::Error异常,调用栈指向Rails的MIME类型解析逻辑。

该错误本质是恶意请求注入了非法的Content-Type头(字符串包含Struts2框架代码片段,大概率是自动化漏洞扫描请求),导致Rails解析请求MIME类型时崩溃。


解决方案

1. 拦截非法请求(推荐)

在Rack中间件层提前过滤包含恶意特征的请求,避免请求进入Rails业务逻辑:

# config/application.rb
class InvalidContentTypeBlocker
  def initialize(app)
    @app = app
  end

  def call(env)
    content_type = env['CONTENT_TYPE']
    # 匹配恶意请求的特征字符串
    if content_type&.include?("{#context") || content_type&.match?(/com\.opensymphony\.xwork2/)
      return [400, {'Content-Type' => 'text/plain'}, ['Invalid Request']]
    end
    @app.call(env)
  end
end

module GaibuEc
  class Application < Rails::Application
    # 将中间件插入到最前面,优先处理请求
    config.middleware.insert_before 0, InvalidContentTypeBlocker
    # ...其他原有配置
  end
end

2. 增强MIME解析容错性

通过Monkey Patch修复Rails的MIME类型解析逻辑,捕获无效MIME类型异常并返回默认值:

# config/initializers/mime_type_patch.rb
module MimeTypePatch
  def lookup(string, fallback = nil)
    super
  rescue Mime::Type::InvalidMimeType
    # 遇到无效类型时返回text/plain,或使用传入的fallback值
    fallback || Mime::Type.lookup('text/plain')
  end
end

Mime::Type.singleton_class.prepend(MimeTypePatch)

3. 封禁恶意IP

查看服务器访问日志(如Nginx日志、Rails日志),定位触发异常的请求IP,在防火墙或Nginx层面封禁这些IP,从源头阻止恶意扫描。

4. 升级Rails版本

将Rails 6.0.0升级到同分支的最新稳定版(如6.0.6.1),新版本可能修复了MIME解析的边界处理问题,提升框架的容错能力。


内容的提问来源于stack exchange,提问作者Vishal Aher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:10:35