20663: Use set operations for group management
[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 keys = ''
50
51 begin
52   debug = false
53   if options[:"debug"]
54     debug = true
55   end
56   arv = Arvados.new({ :suppress_ssl_warnings => false })
57   logincluster_host = ENV['ARVADOS_API_HOST']
58   logincluster_name = arv.cluster_config['Login']['LoginCluster'] or ''
59   # Requiring the fuse group was previous hardcoded behavior
60   minimum_groups = arv.cluster_config['Login']['SyncRequiredGroups'] || ['fuse']
61
62   if logincluster_name != '' and logincluster_name != arv.cluster_config['ClusterID']
63     logincluster_host = arv.cluster_config['RemoteClusters'][logincluster_name]['Host']
64   end
65   logincluster_arv = Arvados.new({ :api_host => logincluster_host,
66                                    :suppress_ssl_warnings => false })
67
68   vm_uuid = ENV['ARVADOS_VIRTUAL_MACHINE_UUID']
69
70   logins = arv.virtual_machine.logins(:uuid => vm_uuid)[:items]
71   logins = [] if logins.nil?
72   logins = logins.reject { |l| l[:username].nil? or l[:hostname].nil? or l[:virtual_machine_uuid] != vm_uuid }
73
74   # No system users
75   uid_min = 1000
76   open("/etc/login.defs", encoding: "utf-8") do |login_defs|
77     login_defs.each_line do |line|
78       next unless match = /^UID_MIN\s+(\S+)$/.match(line)
79       if match[1].start_with?("0x")
80         base = 16
81       elsif match[1].start_with?("0")
82         base = 8
83       else
84         base = 10
85       end
86       new_uid_min = match[1].to_i(base)
87       uid_min = new_uid_min if (new_uid_min > 0)
88     end
89   end
90
91   pwnam = Hash.new()
92   logins.reject! do |l|
93     if not pwnam[l[:username]]
94       begin
95         pwnam[l[:username]] = Etc.getpwnam(l[:username])
96       rescue
97         if options[:"skip-missing-users"]
98           STDERR.puts "Account #{l[:username]} not found. Skipping"
99           true
100         end
101       else
102         if pwnam[l[:username]].uid < uid_min
103           STDERR.puts "Account #{l[:username]} uid #{pwnam[l[:username]].uid} < uid_min #{uid_min}. Skipping" if debug
104           true
105         end
106       end
107     end
108   end
109   keys = Hash.new()
110
111   # Collect all keys
112   logins.each do |l|
113     STDERR.puts("Considering #{l[:username]} ...") if debug
114     keys[l[:username]] = Array.new() if not keys.has_key?(l[:username])
115     key = l[:public_key]
116     if !key.nil?
117       # Handle putty-style ssh public keys
118       key.sub!(/^(Comment: "r[^\n]*\n)(.*)$/m,'ssh-rsa \2 \1')
119       key.sub!(/^(Comment: "d[^\n]*\n)(.*)$/m,'ssh-dss \2 \1')
120       key.gsub!(/\n/,'')
121       key.strip
122
123       keys[l[:username]].push(key) if not keys[l[:username]].include?(key)
124     end
125   end
126
127   seen = Hash.new()
128
129   all_groups = []
130   current_user_groups = Hash.new { |hash, key| hash[key] = [] }
131   while (ent = Etc.getgrent()) do
132     all_groups << ent.name
133     ent.mem.each do |member|
134       current_user_groups[member] << ent.name
135     end
136   end
137   Etc.endgrent()
138
139   logins.each do |l|
140     next if seen[l[:username]]
141     seen[l[:username]] = true
142
143     username = l[:username]
144
145     unless pwnam[l[:username]]
146       STDERR.puts "Creating account #{l[:username]}"
147       # Create new user
148       out, st = Open3.capture2e("useradd", "-m",
149                 "-c", username,
150                 "-s", "/bin/bash",
151                 username)
152       if st.exitstatus != 0
153         STDERR.puts "Account creation failed for #{l[:username]}:\n#{out}"
154         next
155       end
156       begin
157         pwnam[username] = Etc.getpwnam(username)
158       rescue => e
159         STDERR.puts "Created account but then getpwnam() failed for #{l[:username]}: #{e}"
160         raise
161       end
162     end
163
164     user_gid = pwnam[username].gid
165     homedir = pwnam[l[:username]].dir
166     if !File.exist?(homedir)
167       STDERR.puts "Cannot set up user #{username} because their home directory #{homedir} does not exist. Skipping."
168       next
169     end
170
171     have_groups = current_user_groups[username]
172     want_groups = l[:groups] || []
173     want_groups |= minimum_groups
174     want_groups &= all_groups
175
176     (want_groups - have_groups).each do |addgroup|
177       # User should be in group, but isn't, so add them.
178       STDERR.puts "Add user #{username} to #{addgroup} group"
179       out, st = Open3.capture2e("usermod", "-aG", addgroup, username)
180       if st.exitstatus != 0
181         STDERR.puts "Failed to add #{username} to #{addgroup} group:\n#{out}"
182       end
183     end
184
185     (have_groups - want_groups).each do |removegroup|
186       # User is in a group, but shouldn't be, so remove them.
187       STDERR.puts "Remove user #{username} from #{removegroup} group"
188       out, st = Open3.capture2e("gpasswd", "-d", username, removegroup)
189       if st.exitstatus != 0
190         STDERR.puts "Failed to remove user #{username} from #{removegroup} group:\n#{out}"
191       end
192     end
193
194     userdotssh = File.join(homedir, ".ssh")
195     ensure_dir(userdotssh, 0700, username, user_gid)
196
197     newkeys = "###\n###\n" + keys[l[:username]].join("\n") + "\n###\n###\n"
198
199     keysfile = File.join(userdotssh, "authorized_keys")
200     begin
201       oldkeys = File.read(keysfile)
202     rescue Errno::ENOENT
203       oldkeys = ""
204     end
205
206     if options[:exclusive]
207       newkeys = exclusive_banner + newkeys
208     elsif oldkeys.start_with?(exclusive_banner)
209       newkeys = start_banner + newkeys + end_banner
210     elsif (m = /^(.*?\n|)#{start_banner}(.*?\n|)#{end_banner}(.*)/m.match(oldkeys))
211       newkeys = m[1] + start_banner + newkeys + end_banner + m[3]
212     else
213       newkeys = start_banner + newkeys + end_banner + oldkeys
214     end
215
216     if oldkeys != newkeys then
217       File.open(keysfile, 'w', 0600) do |f|
218         f.write(newkeys)
219       end
220       FileUtils.chown(username, user_gid, keysfile)
221     end
222
223     userdotconfig = File.join(homedir, ".config")
224     ensure_dir(userdotconfig, 0755, username, user_gid)
225     configarvados = File.join(userdotconfig, "arvados")
226     ensure_dir(configarvados, 0700, username, user_gid)
227
228     tokenfile = File.join(configarvados, "settings.conf")
229
230     begin
231       STDERR.puts "Processing #{tokenfile} ..." if debug
232       newToken = false
233       if File.exist?(tokenfile)
234         # check if the token is still valid
235         myToken = ENV["ARVADOS_API_TOKEN"]
236         userEnv = File.read(tokenfile)
237         if (m = /^ARVADOS_API_TOKEN=(.*?\n)/m.match(userEnv))
238           begin
239             tmp_arv = Arvados.new({ :api_host => logincluster_host,
240                                     :api_token => (m[1]),
241                                     :suppress_ssl_warnings => false })
242             tmp_arv.user.current
243           rescue Arvados::TransactionFailedError => e
244             if e.to_s =~ /401 Unauthorized/
245               STDERR.puts "Account #{l[:username]} token not valid, creating new token."
246               newToken = true
247             else
248               raise
249             end
250           end
251         end
252       elsif !File.exist?(tokenfile) || options[:"rotate-tokens"]
253         STDERR.puts "Account #{l[:username]} token file not found, creating new token."
254         newToken = true
255       end
256       if newToken
257         aca_params = {owner_uuid: l[:user_uuid], api_client_id: 0}
258         if options[:"token-lifetime"] && options[:"token-lifetime"] > 0
259           aca_params.merge!(expires_at: (Time.now + options[:"token-lifetime"]))
260         end
261         user_token = logincluster_arv.api_client_authorization.create(api_client_authorization: aca_params)
262         File.open(tokenfile, 'w', 0600) do |f|
263           f.write("ARVADOS_API_HOST=#{ENV['ARVADOS_API_HOST']}\n")
264           f.write("ARVADOS_API_TOKEN=v2/#{user_token[:uuid]}/#{user_token[:api_token]}\n")
265         end
266         FileUtils.chown(username, user_gid, tokenfile)
267       end
268     rescue => e
269       STDERR.puts "Error setting token for #{l[:username]}: #{e}"
270     end
271   end
272
273 rescue Exception => bang
274   puts "Error: " + bang.to_s
275   puts bang.backtrace.join("\n")
276   exit 1
277 end