MiniProfiler / rack-mini-profiler

Profiler for your development and production Ruby rack apps.
MIT License
3.68k stars 400 forks source link

Assets served from Rails deauthorizing client-side profiler #613

Open Blayr opened 1 month ago

Blayr commented 1 month ago

When trying to validate my

Rack::MiniProfiler.config.authorization_mode = :allow_authorized

implementation in my development environment, all my /mini-profiler-resources/results requests were failing despite my ApplicationController doing Rack::MiniProfiler.authorize_request in a before_action on every request. After some investigating I found that when loading my assets (via rails), they responded with a Set-Cookie header that was deleting my __profilin cookie.

Screenshot 2024-05-09 at 4 31 57 PM Screenshot 2024-05-09 at 4 30 35 PM

Even though my assets path was included in the skip_paths variable automatically and the skip_it variable was set to true the header to delete the cookie would still be set in handle_cookie, deauthorizing the client when the server loaded the asset.

https://github.com/MiniProfiler/rack-mini-profiler/blob/5e42a57acab20125f910c0f29d82f19e7220ff31/lib/mini_profiler.rb#L168C1-L180C10

      skip_it = matches_action?('skip', env) || (
        @config.skip_paths &&
        @config.skip_paths.any? do |p|
          if p.instance_of?(String)
            path.start_with?(p)
          elsif p.instance_of?(Regexp)
            p.match?(path)
          end
        end
      )
      if skip_it
        return client_settings.handle_cookie(@app.call(env))
      end

https://github.com/MiniProfiler/rack-mini-profiler/blob/5e42a57acab20125f910c0f29d82f19e7220ff31/lib/mini_profiler/client_settings.rb#L42C1-L56C10

      def handle_cookie(result)
        status, headers, _body = result

        if (MiniProfiler.config.authorization_mode == :allow_authorized && !MiniProfiler.request_authorized?)
          # this is non-obvious, don't kill the profiling cookie on errors or short requests
          # this ensures that stuff that never reaches the rails stack does not kill profiling
          if status.to_i >= 200 && status.to_i < 300 && ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - @start) > 0.1)
            discard_cookie!(headers)
          end
        else
          write!(headers)
        end

        result
      end

I created a patch for my own company to avoid deauthorizing specifically for that handle_cookie call, however I'm not sure if that is appropriate for the other condition checked in the same area as the skip_paths is checked. Hopefully i'm not missing some critical setup step that caused this.

https://github.com/MiniProfiler/rack-mini-profiler/compare/master...Vidcruiter:rack-mini-profiler:master