18013: the db:check_long_lived_tokens and db:fix_long_lived_tokens rake
[arvados.git] / services / api / lib / tasks / manage_long_lived_tokens.rake
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 # Tasks that can be useful when changing token expiration policies by assigning
6 # a non-zero value to Login.TokenLifetime config.
7
8 require 'set'
9 require 'current_api_client'
10
11 namespace :db do
12   desc "Apply expiration policy on long lived tokens"
13   task fix_long_lived_tokens: :environment do
14     lifetime = Rails.configuration.API.MaxTokenLifetime
15     if lifetime.nil? or lifetime == 0
16       lifetime = Rails.configuration.Login.TokenLifetime
17     end
18     if lifetime.nil? or lifetime == 0
19       puts("No expiration policy set (API.MaxTokenLifetime nor Login.TokenLifetime is set), nothing to do.")
20       next
21     end
22     exp_date = Time.now + lifetime
23     puts("Setting token expiration to: #{exp_date}")
24     token_count = 0
25     ll_tokens(lifetime).each do |auth|
26       if auth.user.nil?
27         printf("*** WARNING, found ApiClientAuthorization with invalid user: auth id: %d, user id: %d\n", auth.id, auth.user_id)
28         next
29       end
30       if (auth.user.uuid =~ /-tpzed-000000000000000/).nil?
31         CurrentApiClientHelper.act_as_system_user do
32           auth.update_attributes!(expires_at: exp_date)
33         end
34         token_count += 1
35       end
36     end
37     puts("#{token_count} tokens updated.")
38   end
39
40   desc "Show users with long lived tokens"
41   task check_long_lived_tokens: :environment do
42     lifetime = Rails.configuration.API.MaxTokenLifetime
43     if lifetime.nil? or lifetime == 0
44       lifetime = Rails.configuration.Login.TokenLifetime
45     end
46     if lifetime.nil? or lifetime == 0
47       puts("No expiration policy set (API.MaxTokenLifetime nor Login.TokenLifetime is set), nothing to do.")
48       next
49     end
50     user_ids = Set.new()
51     token_count = 0
52     ll_tokens(lifetime).each do |auth|
53       if auth.user.nil?
54         printf("*** WARNING, found ApiClientAuthorization with invalid user: auth id: %d, user id: %d\n", auth.id, auth.user_id)
55         next
56       end
57       if not auth.user.nil? and (auth.user.uuid =~ /-tpzed-000000000000000/).nil?
58         user_ids.add(auth.user_id)
59         token_count += 1
60       end
61     end
62
63     if user_ids.size > 0
64       puts("Found #{token_count} long-lived tokens from users:")
65       user_ids.each do |uid|
66         u = User.find(uid)
67         puts("#{u.username},#{u.email},#{u.uuid}") if !u.nil?
68       end
69     else
70       puts("No long-lived tokens found.")
71     end
72   end
73
74   def ll_tokens(lifetime)
75     query = ApiClientAuthorization.where(expires_at: nil)
76     query = query.or(ApiClientAuthorization.where("expires_at > ?", Time.now + lifetime))
77     query
78   end
79 end