Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to provide regexp instead of just substrings for exclude #29

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions lib/rack/jwt/auth.rb
Original file line number Diff line number Diff line change
Expand Up @@ -152,22 +152,31 @@ def check_exclude_type!
end

@exclude.each do |x|
unless x.is_a?(String)
raise ArgumentError, 'each exclude Array element must be a String'
unless x.is_a?(String) || x.is_a?(Regexp)
raise ArgumentError, 'each exclude Array element must be a String or a Regexp'
end

if x.empty?
if x.to_s.empty?
raise ArgumentError, 'each exclude Array element must not be empty'
end

unless x.start_with?('/')
# Perhaps surprisingly, Regexp#inspect actually produces the more
# natural version of the string than #to_s.
as_s = x.is_a?(Regexp) ? x.inspect : x
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not entirely sure about this. %r{stati+} turns into /stati+ so this always passes for Regexp. Which is probably not what we want. We could check for /\/stati in case of a regexp, but it becomes icky quite fast.

Do we want to check if it starts with a / for regexp at all?

unless as_s.start_with?('/')
raise ArgumentError, 'each exclude Array element must start with a /'
end
end
end

def path_matches_excluded_path?(env)
@exclude.any? { |ex| env['PATH_INFO'].start_with?(ex) }
@exclude.any? do |ex|
if ex.is_a?(Regexp)
ex.match?(env['PATH_INFO'])
else
env['PATH_INFO'].start_with?(ex)
end
end
end

def valid_auth_header?(env)
Expand Down
9 changes: 9 additions & 0 deletions spec/exclusion_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,15 @@
end
end

describe 'passes through matching regexp' do
let(:app) { Rack::JWT::Auth.new(inner_app, secret: secret, exclude: [/stati+/]) }

it 'returns a 200' do
get('/static')
expect(last_response.status).to eq 200
end
end

describe 'passes through matching exact path with trailing slash' do
let(:app) { Rack::JWT::Auth.new(inner_app, secret: secret, exclude: ['/static']) }

Expand Down