21700: Install Bundler system-wide in Rails postinst
[arvados.git] / services / login-sync / bin / arvados-login-sync
1 #!/usr/bin/env ruby
2 # Copyright (C) The Arvados Authors. All rights reserved.
3 #
4 # SPDX-License-Identifier: AGPL-3.0
5
6 require 'rubygems'
7 require 'pp'
8 require 'arvados'
9 require 'etc'
10 require 'fileutils'
11 require 'yaml'
12 require 'optparse'
13 require 'open3'
14
15 def ensure_dir(path, mode, owner, group)
16   begin
17     Dir.mkdir(path, mode)
18   rescue Errno::EEXIST
19     # No change needed
20     false
21   else
22     FileUtils.chown(owner, group, path)
23     true
24   end
25 end
26
27 req_envs = %w(ARVADOS_API_HOST ARVADOS_API_TOKEN ARVADOS_VIRTUAL_MACHINE_UUID)
28 req_envs.each do |k|
29   unless ENV[k]
30     abort "Fatal: These environment vars must be set: #{req_envs}"
31   end
32 end
33
34 options = {}
35 OptionParser.new do |parser|
36   parser.on('--exclusive', 'Manage SSH keys file exclusively.')
37   parser.on('--rotate-tokens', 'Force a rotation of all user tokens.')
38   parser.on('--skip-missing-users', "Don't try to create any local accounts.")
39   parser.on('--token-lifetime SECONDS', 'Create user tokens that expire after SECONDS.', Integer)
40   parser.on('--debug', 'Enable debug output')
41 end.parse!(into: options)
42
43 exclusive_banner = "#######################################################################################
44 #  THIS FILE IS MANAGED BY #{$0} -- CHANGES WILL BE OVERWRITTEN  #
45 #######################################################################################\n\n"
46 start_banner = "### BEGIN Arvados-managed keys -- changes between markers will be overwritten\n"
47 end_banner = "### END Arvados-managed keys -- changes between markers will be overwritten\n"
48
49 actions = {
50   # These names correspond to the names in the cluster Users configuration.
51   # Managing everything was the original behavior.
52   SyncUserAccounts: true,
53   SyncUserGroups: true,
54   SyncUserSSHKeys: true,
55   SyncUserAPITokens: true,
56 }
57
58 keys = ''
59
60 begin
61   debug = false
62   if options[:"debug"]
63     debug = true
64   end
65   arv = Arvados.new({ :suppress_ssl_warnings => false })
66   logincluster_host = ENV['ARVADOS_API_HOST']
67   logincluster_name = arv.cluster_config['Login']['LoginCluster'] or ''
68
69   # Requiring the fuse group was previous hardcoded behavior
70   minimum_groups = arv.cluster_config['Users']['SyncRequiredGroups'] || ['fuse']
71   ignored_groups = arv.cluster_config['Users']['SyncIgnoredGroups'] || []
72   (minimum_groups & ignored_groups).each do |group_name|
73     STDERR.puts "WARNING: #{group_name} is listed in both SyncRequiredGroups and SyncIgnoredGroups. It will be ignored."
74   end
75
76   actions.each_pair do |key, default|
77     actions[key] = arv.cluster_config['Users'].fetch(key.to_s, default)
78   end
79
80   if logincluster_name != '' and logincluster_name != arv.cluster_config['ClusterID']
81     logincluster_host = arv.cluster_config['RemoteClusters'][logincluster_name]['Host']
82   end
83   logincluster_arv = Arvados.new({ :api_host => logincluster_host,
84                                    :suppress_ssl_warnings => false })
85
86   vm_uuid = ENV['ARVADOS_VIRTUAL_MACHINE_UUID']
87
88   logins = arv.virtual_machine.logins(:uuid => vm_uuid)[:items]
89   logins = [] if logins.nil?
90   logins = logins.reject { |l| l[:username].nil? or l[:hostname].nil? or l[:virtual_machine_uuid] != vm_uuid }
91
92   # No system users
93   uid_min = 1000
94   open("/etc/login.defs", encoding: "utf-8") do |login_defs|
95     login_defs.each_line do |line|
96       next unless match = /^UID_MIN\s+(\S+)$/.match(line)
97       if match[1].start_with?("0x")
98         base = 16
99       elsif match[1].start_with?("0")
100         base = 8
101       else
102         base = 10
103       end
104       new_uid_min = match[1].to_i(base)
105       uid_min = new_uid_min if (new_uid_min > 0)
106     end
107   end
108
109   pwnam = Hash.new()
110   logins.reject! do |l|
111     if not pwnam[l[:username]]
112       begin
113         pwnam[l[:username]] = Etc.getpwnam(l[:username])
114       rescue
115         if options[:"skip-missing-users"]
116           STDERR.puts "Account #{l[:username]} not found. Skipping"
117           true
118         end
119       else
120         if pwnam[l[:username]].uid < uid_min
121           STDERR.puts "Account #{l[:username]} uid #{pwnam[l[:username]].uid} < uid_min #{uid_min}. Skipping" if debug
122           true
123         end
124       end
125     end
126   end
127   keys = Hash.new()
128
129   # Collect all keys
130   logins.each do |l|
131     STDERR.puts("Considering #{l[:username]} ...") if debug
132     keys[l[:username]] = Array.new() if not keys.has_key?(l[:username])
133     key = l[:public_key]
134     if !key.nil?
135       # Handle putty-style ssh public keys
136       key.sub!(/^(Comment: "r[^\n]*\n)(.*)$/m,'ssh-rsa \2 \1')
137       key.sub!(/^(Comment: "d[^\n]*\n)(.*)$/m,'ssh-dss \2 \1')
138       key.gsub!(/\n/,'')
139       key.strip
140
141       keys[l[:username]].push(key) if not keys[l[:username]].include?(key)
142     end
143   end
144
145   seen = Hash.new()
146
147   all_groups = []
148   current_user_groups = Hash.new { |hash, key| hash[key] = [] }
149   while (ent = Etc.getgrent()) do
150     all_groups << ent.name
151     ent.mem.each do |member|
152       current_user_groups[member] << ent.name
153     end
154   end
155   Etc.endgrent()
156
157   logins.each do |l|
158     next if seen[l[:username]]
159     seen[l[:username]] = true
160
161     username = l[:username]
162
163     unless pwnam[l[:username]]
164       unless actions[:SyncUserAccounts]
165         STDERR.puts "User #{username} does not exist and SyncUserAccounts=false. Skipping."
166         next
167       end
168       STDERR.puts "Creating account #{l[:username]}"
169       # Create new user
170       out, st = Open3.capture2e("useradd", "-m",
171                 "-c", username,
172                 "-s", "/bin/bash",
173                 username)
174       if st.exitstatus != 0
175         STDERR.puts "Account creation failed for #{l[:username]}:\n#{out}"
176         next
177       end
178       begin
179         pwnam[username] = Etc.getpwnam(username)
180       rescue => e
181         STDERR.puts "Created account but then getpwnam() failed for #{l[:username]}: #{e}"
182         raise
183       end
184     end
185
186     user_gid = pwnam[username].gid
187     homedir = pwnam[l[:username]].dir
188     if !File.exist?(homedir)
189       STDERR.puts "Cannot set up user #{username} because their home directory #{homedir} does not exist. Skipping."
190       next
191     end
192
193     if actions[:SyncUserGroups]
194       have_groups = current_user_groups[username] - ignored_groups
195       want_groups = l[:groups] || []
196       want_groups |= minimum_groups
197       want_groups -= ignored_groups
198       want_groups &= all_groups
199
200       (want_groups - have_groups).each do |addgroup|
201         # User should be in group, but isn't, so add them.
202         STDERR.puts "Add user #{username} to #{addgroup} group"
203         out, st = Open3.capture2e("usermod", "-aG", addgroup, username)
204         if st.exitstatus != 0
205           STDERR.puts "Failed to add #{username} to #{addgroup} group:\n#{out}"
206         end
207       end
208
209       (have_groups - want_groups).each do |removegroup|
210         # User is in a group, but shouldn't be, so remove them.
211         STDERR.puts "Remove user #{username} from #{removegroup} group"
212         out, st = Open3.capture2e("gpasswd", "-d", username, removegroup)
213         if st.exitstatus != 0
214           STDERR.puts "Failed to remove user #{username} from #{removegroup} group:\n#{out}"
215         end
216       end
217     end
218
219     if actions[:SyncUserSSHKeys]
220       userdotssh = File.join(homedir, ".ssh")
221       ensure_dir(userdotssh, 0700, username, user_gid)
222
223       newkeys = "###\n###\n" + keys[l[:username]].join("\n") + "\n###\n###\n"
224
225       keysfile = File.join(userdotssh, "authorized_keys")
226       begin
227         oldkeys = File.read(keysfile)
228       rescue Errno::ENOENT
229         oldkeys = ""
230       end
231
232       if options[:exclusive]
233         newkeys = exclusive_banner + newkeys
234       elsif oldkeys.start_with?(exclusive_banner)
235         newkeys = start_banner + newkeys + end_banner
236       elsif (m = /^(.*?\n|)#{start_banner}(.*?\n|)#{end_banner}(.*)/m.match(oldkeys))
237         newkeys = m[1] + start_banner + newkeys + end_banner + m[3]
238       else
239         newkeys = start_banner + newkeys + end_banner + oldkeys
240       end
241
242       if oldkeys != newkeys then
243         File.open(keysfile, 'w', 0600) do |f|
244           f.write(newkeys)
245         end
246         FileUtils.chown(username, user_gid, keysfile)
247       end
248     end
249
250     if actions[:SyncUserAPITokens]
251       userdotconfig = File.join(homedir, ".config")
252       ensure_dir(userdotconfig, 0755, username, user_gid)
253       configarvados = File.join(userdotconfig, "arvados")
254       ensure_dir(configarvados, 0700, username, user_gid)
255
256       tokenfile = File.join(configarvados, "settings.conf")
257
258       begin
259         STDERR.puts "Processing #{tokenfile} ..." if debug
260         newToken = false
261         if File.exist?(tokenfile)
262           # check if the token is still valid
263           myToken = ENV["ARVADOS_API_TOKEN"]
264           userEnv = File.read(tokenfile)
265           if (m = /^ARVADOS_API_TOKEN=(.*?\n)/m.match(userEnv))
266             begin
267               tmp_arv = Arvados.new({ :api_host => logincluster_host,
268                                       :api_token => (m[1]),
269                                       :suppress_ssl_warnings => false })
270               tmp_arv.user.current
271             rescue Arvados::TransactionFailedError => e
272               if e.to_s =~ /401 Unauthorized/
273                 STDERR.puts "Account #{l[:username]} token not valid, creating new token."
274                 newToken = true
275               else
276                 raise
277               end
278             end
279           end
280         elsif !File.exist?(tokenfile) || options[:"rotate-tokens"]
281           STDERR.puts "Account #{l[:username]} token file not found, creating new token."
282           newToken = true
283         end
284         if newToken
285           aca_params = {owner_uuid: l[:user_uuid], api_client_id: 0}
286           if options[:"token-lifetime"] && options[:"token-lifetime"] > 0
287             aca_params.merge!(expires_at: (Time.now + options[:"token-lifetime"]))
288           end
289           user_token = logincluster_arv.api_client_authorization.create(api_client_authorization: aca_params)
290           File.open(tokenfile, 'w', 0600) do |f|
291             f.write("ARVADOS_API_HOST=#{ENV['ARVADOS_API_HOST']}\n")
292             f.write("ARVADOS_API_TOKEN=v2/#{user_token[:uuid]}/#{user_token[:api_token]}\n")
293           end
294           FileUtils.chown(username, user_gid, tokenfile)
295         end
296       rescue => e
297         STDERR.puts "Error setting token for #{l[:username]}: #{e}"
298       end
299     end
300   end
301
302 rescue Exception => bang
303   puts "Error: " + bang.to_s
304   puts bang.backtrace.join("\n")
305   exit 1
306 end