From a9cda0f947c41b6c01ea844229010c83d3afaf2f Mon Sep 17 00:00:00 2001 From: Sam Date: Thu, 20 Nov 2014 15:21:49 +1100 Subject: [PATCH] FEATURE: allow restricting API keys to a particular range --- lib/auth/default_current_user_provider.rb | 8 +++++-- .../default_current_user_provider_spec.rb | 21 +++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/lib/auth/default_current_user_provider.rb b/lib/auth/default_current_user_provider.rb index 94c7a8e914a..9772a037d7a 100644 --- a/lib/auth/default_current_user_provider.rb +++ b/lib/auth/default_current_user_provider.rb @@ -107,12 +107,16 @@ class Auth::DefaultCurrentUserProvider api_key = ApiKey.where(key: api_key_value).includes(:user).first if api_key api_username = request["api_username"] + + if api_key.allowed_ips.present? && !api_key.allowed_ips.any?{|ip| ip.include?(request.ip)} + Rails.logger.warn("Unauthorized API access: #{api_username} ip address: #{request.ip}") + return nil + end + if api_key.user api_key.user if !api_username || (api_key.user.username_lower == api_username.downcase) elsif api_username User.find_by(username_lower: api_username.downcase) - else - nil end end end diff --git a/spec/components/auth/default_current_user_provider_spec.rb b/spec/components/auth/default_current_user_provider_spec.rb index ccad63bbedc..99c5e2e96c0 100644 --- a/spec/components/auth/default_current_user_provider_spec.rb +++ b/spec/components/auth/default_current_user_provider_spec.rb @@ -31,6 +31,27 @@ describe Auth::DefaultCurrentUserProvider do }.to raise_error(Discourse::InvalidAccess) end + it "raises for a user with a mismatching ip" do + user = Fabricate(:user) + ApiKey.create!(key: "hello", user_id: user.id, created_by_id: -1, allowed_ips: ['10.0.0.0/24']) + + expect{ + provider("/?api_key=hello&api_username=#{user.username.downcase}", "REMOTE_ADDR" => "10.1.0.1").current_user + }.to raise_error(Discourse::InvalidAccess) + + end + + it "allows a user with a matching ip" do + user = Fabricate(:user) + ApiKey.create!(key: "hello", user_id: user.id, created_by_id: -1, allowed_ips: ['10.0.0.0/24']) + + found_user = provider("/?api_key=hello&api_username=#{user.username.downcase}", + "REMOTE_ADDR" => "10.0.0.22").current_user + + found_user.id.should == user.id + + end + it "finds a user for a correct system api key" do user = Fabricate(:user) ApiKey.create!(key: "hello", created_by_id: -1)