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 User.revoke_sessions #20601

Merged
merged 5 commits into from
Oct 9, 2020
Merged
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
38 changes: 37 additions & 1 deletion app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class User < ApplicationRecord
has_many :unseen_notification_recipients, -> { unseen }, :class_name => 'NotificationRecipient'
has_many :unseen_notifications, :through => :unseen_notification_recipients, :source => :notification
has_many :authentications, :foreign_key => :evm_owner_id, :dependent => :nullify, :inverse_of => :evm_owner
has_many :sessions, :dependent => :destroy
belongs_to :current_group, :class_name => "MiqGroup"
has_and_belongs_to_many :miq_groups
scope :superadmins, lambda {
Expand Down Expand Up @@ -206,7 +207,42 @@ def self.authenticator(username = nil)
end

def self.authenticate(username, password, request = nil, options = {})
authenticator(username).authenticate(username, password, request, options)
user = authenticator(username).authenticate(username, password, request, options)
user.try(:link_to_session, request)

user
end

def link_to_session(request)
return unless request
return unless (session_id = request.session_options[:id])

sessions << Session.find_or_create_by(:session_id => session_id)
NickLaMuro marked this conversation as resolved.
Show resolved Hide resolved
NickLaMuro marked this conversation as resolved.
Show resolved Hide resolved
end

def broadcast_revoke_sessions
if Settings.server.session_store == "cache"
MiqQueue.broadcast(
:class_name => self.class.name,
:instance_id => id,
:method_name => :revoke_sessions
)
else
# If using SQL or Memory, the sessions don't need to (or can't) be
# revoked via a broadcast since the session/token stores are not server
# specific, so execute it inline.
Fryguy marked this conversation as resolved.
Show resolved Hide resolved
revoke_sessions
end
end

def revoke_sessions
current_sessions = Session.where(:user_id => id)
ManageIQ::Session.revoke(current_sessions.map(&:session_id))
current_sessions.destroy_all
Copy link
Member

Choose a reason for hiding this comment

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

Wondering if this should be in a transaction?

Copy link
Member Author

Choose a reason for hiding this comment

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

Probably not a bad idea.

Copy link
Member Author

Choose a reason for hiding this comment

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

Actually, I am going to hold off on this.

While a transaction would be nice, unfortunately, there is a possibility it will be not function as expected, since ManageIQ::Session could have a .store of memcached, so the transaction wouldn't be "fully reverted" if we were to wrap both .revoke and .destroy_all in a single transaction.

I think the .destroy_all would be in it's own transaction, but I could be wrong so I don't know if there is any value of wrapping just that line.


TokenStore.token_caches.each do |_, token_store|
NickLaMuro marked this conversation as resolved.
Show resolved Hide resolved
token_store.delete_all_for_user(userid)
end
end

def self.authenticate_with_http_basic(username, password, request = nil, options = {})
Expand Down
6 changes: 3 additions & 3 deletions lib/token_manager.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ def gen_token(token_options = {})
ttl = token_options.delete(:token_ttl_override) || token_ttl
token_data = {:token_ttl => ttl, :expires_on => Time.now.utc + ttl}

token_store.write(token,
token_data.merge!(prune_token_options(token_options)),
:expires_in => token_ttl)
token_store.create_user_token(token,
token_data.merge!(prune_token_options(token_options)),
:expires_in => token_ttl)
token
end

Expand Down
35 changes: 31 additions & 4 deletions lib/token_store.rb
Original file line number Diff line number Diff line change
@@ -1,20 +1,47 @@
class TokenStore
@token_caches = {} # Hash of Memory/Dalli Store Caches, Keyed by namespace
module KeyValueHelpers
Copy link
Member

Choose a reason for hiding this comment

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

thanks - this is much nicer than the individual monkey patches

def delete_all_for_user(userid)
Array(read("tokens_for_#{userid}")).each do |token|
delete(token)
end

delete("tokens_for_#{userid}")
end

def create_user_token(token, data, options)
write(token, data, options)
ensure
if data[:userid]
user_tokens_cache_key = "tokens_for_#{data[:userid]}"
user_tokens_cache = read(user_tokens_cache_key) || []
user_tokens_cache << token
Copy link
Member

Choose a reason for hiding this comment

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

This is really tricky in a multi-threaded environment particularly with memcached. As two competing threads come in, they can't step on each other.

This was sort of what I was hinting at in the original proposal (#20378 (comment) - see the cross out section on memory_store), where I mentioned for memached we might need to use CAS.

These particular "create an extra index in the memory store" was what we were trying to avoid by storing all of the records in the sessions table regardless of the store type. I'm not against encoding an index in each one instead, but I think each one has nuances.

Copy link
Member

Choose a reason for hiding this comment

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

if we are using multiple memcached instances, then each server will have a unique list of session ids
and has a low likelihood of stepping on another server's toes. Also, every server can not clear the sessions on other memcached servers. Maybe the use cases for problems are simpler in terms of the session store and more complicated in terms of broadcasting to delete all of a user's sessions.

Yes. A single server could have multiple sessions coming live at the same time. Maybe via the api and rails at the same time? I am having trouble coming up with a use case that doesn't seem far fetched.

Before we go super complex on distributed memcached servers, can we entertain using a single session store? Just like we use a single data store (postgres).

write(user_tokens_cache_key, user_tokens_cache)
end
end
end

def self.token_caches
@token_caches ||= {} # Hash of Memory/Dalli Store Caches, Keyed by namespace
end

# only used by TokenManager.token_store
# @return a token store for users
def self.acquire(namespace, token_ttl)
@token_caches[namespace] ||= begin
token_caches[namespace] ||= begin
options = cache_store_options(namespace, token_ttl)
case ::Settings.server.session_store
when "sql"
SqlStore.new(options)
when "memory"
require 'active_support/cache/memory_store'
ActiveSupport::Cache::MemoryStore.new(options)
ActiveSupport::Cache::MemoryStore.new(options).tap do |store|
store.extend KeyValueHelpers
end
when "cache"
require 'active_support/cache/dalli_store'
ActiveSupport::Cache::DalliStore.new(MiqMemcached.server_address, options)
ActiveSupport::Cache::DalliStore.new(MiqMemcached.server_address, options).tap do |store|
store.extend KeyValueHelpers
end
else
raise "unsupported session store type: #{::Settings.server.session_store}"
end
Expand Down
18 changes: 18 additions & 0 deletions lib/token_store/sql_store.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,14 @@ def initialize(options)
@namespace = options.fetch(:namespace)
end

def create_user_token(token, data, options)
write(token, data, options)
end

def write(token, data, _options = nil)
record = Session.find_or_create_by(:session_id => session_key(token))
record.raw_data = data
record.user_id = find_user_by_userid(data[:userid]).try(:id) if data[:userid]
record.save!
end

Expand All @@ -28,12 +33,25 @@ def delete(token)
record.destroy!
end

def delete_all_for_user(userid)
user = find_user_by_userid(userid)
user.sessions.where(Session.arel_table[:session_id].matches("#{@namespace}%", nil, true)).destroy_all
end

private

attr_reader :namespace

def session_key(token)
"#{namespace}:#{token}"
end

def find_user_by_userid(userid)
User.in_my_region.where('lower(userid) = ?', userid.downcase).first
NickLaMuro marked this conversation as resolved.
Show resolved Hide resolved
end

def find_user_by_id(id)
User.in_my_region.where(:id => id).first
end
end
end