2 # Copyright (C) The Arvados Authors. All rights reserved.
4 # SPDX-License-Identifier: AGPL-3.0
15 def ensure_dir(path, mode, owner, group)
22 FileUtils.chown(owner, group, path)
27 req_envs = %w(ARVADOS_API_HOST ARVADOS_API_TOKEN ARVADOS_VIRTUAL_MACHINE_UUID)
30 abort "Fatal: These environment vars must be set: #{req_envs}"
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)
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"
50 # These names correspond to the names in the cluster Users configuration.
51 # Managing everything was the original behavior.
52 SyncUserAccounts: true,
54 SyncUserSSHKeys: true,
55 SyncUserAPITokens: true,
65 arv = Arvados.new({ :suppress_ssl_warnings => false })
66 logincluster_host = ENV['ARVADOS_API_HOST']
67 logincluster_name = arv.cluster_config['Login']['LoginCluster'] or ''
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."
76 actions.each_pair do |key, default|
77 actions[key] = arv.cluster_config['Users'].fetch(key.to_s, default)
80 if logincluster_name != '' and logincluster_name != arv.cluster_config['ClusterID']
81 logincluster_host = arv.cluster_config['RemoteClusters'][logincluster_name]['Host']
83 logincluster_arv = Arvados.new({ :api_host => logincluster_host,
84 :suppress_ssl_warnings => false })
86 vm_uuid = ENV['ARVADOS_VIRTUAL_MACHINE_UUID']
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 }
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")
99 elsif match[1].start_with?("0")
104 new_uid_min = match[1].to_i(base)
105 uid_min = new_uid_min if (new_uid_min > 0)
110 logins.reject! do |l|
111 if not pwnam[l[:username]]
113 pwnam[l[:username]] = Etc.getpwnam(l[:username])
115 if options[:"skip-missing-users"]
116 STDERR.puts "Account #{l[:username]} not found. Skipping"
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
131 STDERR.puts("Considering #{l[:username]} ...") if debug
132 keys[l[:username]] = Array.new() if not keys.has_key?(l[:username])
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')
141 keys[l[:username]].push(key) if not keys[l[:username]].include?(key)
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
158 next if seen[l[:username]]
159 seen[l[:username]] = true
161 username = l[:username]
163 unless pwnam[l[:username]]
164 unless actions[:SyncUserAccounts]
165 STDERR.puts "User #{username} does not exist and SyncUserAccounts=false. Skipping."
168 STDERR.puts "Creating account #{l[:username]}"
170 out, st = Open3.capture2e("useradd", "-m",
174 if st.exitstatus != 0
175 STDERR.puts "Account creation failed for #{l[:username]}:\n#{out}"
179 pwnam[username] = Etc.getpwnam(username)
181 STDERR.puts "Created account but then getpwnam() failed for #{l[:username]}: #{e}"
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."
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
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}"
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}"
219 if actions[:SyncUserSSHKeys]
220 userdotssh = File.join(homedir, ".ssh")
221 ensure_dir(userdotssh, 0700, username, user_gid)
223 newkeys = "###\n###\n" + keys[l[:username]].join("\n") + "\n###\n###\n"
225 keysfile = File.join(userdotssh, "authorized_keys")
227 oldkeys = File.read(keysfile)
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]
239 newkeys = start_banner + newkeys + end_banner + oldkeys
242 if oldkeys != newkeys then
243 File.open(keysfile, 'w', 0600) do |f|
246 FileUtils.chown(username, user_gid, keysfile)
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)
256 tokenfile = File.join(configarvados, "settings.conf")
259 STDERR.puts "Processing #{tokenfile} ..." if debug
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))
267 tmp_arv = Arvados.new({ :api_host => logincluster_host,
268 :api_token => (m[1]),
269 :suppress_ssl_warnings => false })
271 rescue Arvados::TransactionFailedError => e
272 if e.to_s =~ /401 Unauthorized/
273 STDERR.puts "Account #{l[:username]} token not valid, creating new token."
280 elsif !File.exist?(tokenfile) || options[:"rotate-tokens"]
281 STDERR.puts "Account #{l[:username]} token file not found, creating new token."
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"]))
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")
294 FileUtils.chown(username, user_gid, tokenfile)
297 STDERR.puts "Error setting token for #{l[:username]}: #{e}"
302 rescue Exception => bang
303 puts "Error: " + bang.to_s
304 puts bang.backtrace.join("\n")