2 # Copyright (C) The Arvados Authors. All rights reserved.
4 # SPDX-License-Identifier: AGPL-3.0
15 req_envs = %w(ARVADOS_API_HOST ARVADOS_API_TOKEN ARVADOS_VIRTUAL_MACHINE_UUID)
18 abort "Fatal: These environment vars must be set: #{req_envs}"
23 OptionParser.new do |parser|
24 parser.on('--exclusive', 'Manage SSH keys file exclusively.')
25 parser.on('--rotate-tokens', 'Force a rotation of all user tokens.')
26 parser.on('--skip-missing-users', "Don't try to create any local accounts.")
27 parser.on('--token-lifetime SECONDS', 'Create user tokens that expire after SECONDS.', Integer)
28 parser.on('--debug', 'Enable debug output')
29 end.parse!(into: options)
31 exclusive_banner = "#######################################################################################
32 # THIS FILE IS MANAGED BY #{$0} -- CHANGES WILL BE OVERWRITTEN #
33 #######################################################################################\n\n"
34 start_banner = "### BEGIN Arvados-managed keys -- changes between markers will be overwritten\n"
35 end_banner = "### END Arvados-managed keys -- changes between markers will be overwritten\n"
44 arv = Arvados.new({ :suppress_ssl_warnings => false })
45 logincluster_arv = Arvados.new({ :api_host => (ENV['LOGINCLUSTER_ARVADOS_API_HOST'] || ENV['ARVADOS_API_HOST']),
46 :api_token => (ENV['LOGINCLUSTER_ARVADOS_API_TOKEN'] || ENV['ARVADOS_API_TOKEN']),
47 :suppress_ssl_warnings => false })
49 vm_uuid = ENV['ARVADOS_VIRTUAL_MACHINE_UUID']
51 logins = arv.virtual_machine.logins(:uuid => vm_uuid)[:items]
52 logins = [] if logins.nil?
53 logins = logins.reject { |l| l[:username].nil? or l[:hostname].nil? or l[:virtual_machine_uuid] != vm_uuid }
57 open("/etc/login.defs", encoding: "utf-8") do |login_defs|
58 login_defs.each_line do |line|
59 next unless match = /^UID_MIN\s+(\S+)$/.match(line)
60 if match[1].start_with?("0x")
62 elsif match[1].start_with?("0")
67 new_uid_min = match[1].to_i(base)
68 uid_min = new_uid_min if (new_uid_min > 0)
74 if not pwnam[l[:username]]
76 pwnam[l[:username]] = Etc.getpwnam(l[:username])
78 if options[:"skip-missing-users"]
79 STDERR.puts "Account #{l[:username]} not found. Skipping"
83 if pwnam[l[:username]].uid < uid_min
84 STDERR.puts "Account #{l[:username]} uid #{pwnam[l[:username]].uid} < uid_min #{uid_min}. Skipping" if debug
94 STDERR.puts("Considering #{l[:username]} ...") if debug
95 keys[l[:username]] = Array.new() if not keys.has_key?(l[:username])
98 # Handle putty-style ssh public keys
99 key.sub!(/^(Comment: "r[^\n]*\n)(.*)$/m,'ssh-rsa \2 \1')
100 key.sub!(/^(Comment: "d[^\n]*\n)(.*)$/m,'ssh-dss \2 \1')
104 keys[l[:username]].push(key) if not keys[l[:username]].include?(key)
110 current_user_groups = Hash.new
111 while (ent = Etc.getgrent()) do
112 ent.mem.each do |member|
113 current_user_groups[member] ||= Array.new
114 current_user_groups[member].push ent.name
120 next if seen[l[:username]]
121 seen[l[:username]] = true
123 username = l[:username]
125 unless pwnam[l[:username]]
126 STDERR.puts "Creating account #{l[:username]}"
128 out, st = Open3.capture2e("useradd", "-m",
132 if st.exitstatus != 0
133 STDERR.puts "Account creation failed for #{l[:username]}:\n#{out}"
137 pwnam[username] = Etc.getpwnam(username)
139 STDERR.puts "Created account but then getpwnam() failed for #{l[:username]}: #{e}"
144 existing_groups = current_user_groups[username] || []
145 groups = l[:groups] || []
146 # Adding users to the FUSE group has long been hardcoded behavior.
149 groups.select! { |g| Etc.getgrnam(g) rescue false }
151 groups.each do |addgroup|
152 if existing_groups.index(addgroup).nil?
153 # User should be in group, but isn't, so add them.
154 STDERR.puts "Add user #{username} to #{addgroup} group"
155 out, st = Open3.capture2e("usermod", "-aG", addgroup, username)
156 if st.exitstatus != 0
157 STDERR.puts "Failed to add #{username} to #{addgroup} group:\n#{out}"
162 existing_groups.each do |removegroup|
163 if groups.index(removegroup).nil?
164 # User is in a group, but shouldn't be, so remove them.
165 STDERR.puts "Remove user #{username} from #{removegroup} group"
166 out, st = Open3.capture2e("gpasswd", "-d", username, removegroup)
167 if st.exitstatus != 0
168 STDERR.puts "Failed to remove user #{username} from #{removegroup} group:\n#{out}"
173 homedir = pwnam[l[:username]].dir
174 userdotssh = File.join(homedir, ".ssh")
175 Dir.mkdir(userdotssh) if !File.exist?(userdotssh)
177 newkeys = "###\n###\n" + keys[l[:username]].join("\n") + "\n###\n###\n"
179 keysfile = File.join(userdotssh, "authorized_keys")
181 if File.exist?(keysfile)
182 oldkeys = IO::read(keysfile)
187 if options[:exclusive]
188 newkeys = exclusive_banner + newkeys
189 elsif oldkeys.start_with?(exclusive_banner)
190 newkeys = start_banner + newkeys + end_banner
191 elsif (m = /^(.*?\n|)#{start_banner}(.*?\n|)#{end_banner}(.*)/m.match(oldkeys))
192 newkeys = m[1] + start_banner + newkeys + end_banner + m[3]
194 newkeys = start_banner + newkeys + end_banner + oldkeys
197 if oldkeys != newkeys then
198 f = File.new(keysfile, 'w')
203 userdotconfig = File.join(homedir, ".config")
204 if !File.exist?(userdotconfig)
205 Dir.mkdir(userdotconfig)
208 configarvados = File.join(userdotconfig, "arvados")
209 Dir.mkdir(configarvados) if !File.exist?(configarvados)
211 tokenfile = File.join(configarvados, "settings.conf")
214 STDERR.puts "Processing #{tokenfile} ..." if debug
216 if File.exist?(tokenfile)
217 # check if the token is still valid
218 myToken = ENV["ARVADOS_API_TOKEN"]
219 userEnv = IO::read(tokenfile)
220 if (m = /^ARVADOS_API_TOKEN=(.*?\n)/m.match(userEnv))
222 tmp_arv = Arvados.new({ :api_host => (ENV['LOGINCLUSTER_ARVADOS_API_HOST'] || ENV['ARVADOS_API_HOST']),
223 :api_token => (m[1]),
224 :suppress_ssl_warnings => false })
226 rescue Arvados::TransactionFailedError => e
227 if e.to_s =~ /401 Unauthorized/
228 STDERR.puts "Account #{l[:username]} token not valid, creating new token."
235 elsif !File.exist?(tokenfile) || options[:"rotate-tokens"]
236 STDERR.puts "Account #{l[:username]} token file not found, creating new token."
240 aca_params = {owner_uuid: l[:user_uuid], api_client_id: 0}
241 if options[:"token-lifetime"] && options[:"token-lifetime"] > 0
242 aca_params.merge!(expires_at: (Time.now + options[:"token-lifetime"]))
244 user_token = logincluster_arv.api_client_authorization.create(api_client_authorization: aca_params)
245 f = File.new(tokenfile, 'w')
246 f.write("ARVADOS_API_HOST=#{ENV['ARVADOS_API_HOST']}\n")
247 f.write("ARVADOS_API_TOKEN=v2/#{user_token[:uuid]}/#{user_token[:api_token]}\n")
251 STDERR.puts "Error setting token for #{l[:username]}: #{e}"
254 FileUtils.chown_R(l[:username], nil, userdotssh)
255 FileUtils.chown_R(l[:username], nil, userdotconfig)
256 File.chmod(0700, userdotssh)
257 File.chmod(0700, userdotconfig)
258 File.chmod(0700, configarvados)
259 File.chmod(0750, homedir)
260 File.chmod(0600, keysfile)
261 if File.exist?(tokenfile)
262 File.chmod(0600, tokenfile)
266 rescue Exception => bang
267 puts "Error: " + bang.to_s
268 puts bang.backtrace.join("\n")