2 # Copyright (C) The Arvados Authors. All rights reserved.
4 # SPDX-License-Identifier: AGPL-3.0
14 req_envs = %w(ARVADOS_API_HOST ARVADOS_API_TOKEN ARVADOS_VIRTUAL_MACHINE_UUID)
17 abort "Fatal: These environment vars must be set: #{req_envs}"
22 OptionParser.new do |parser|
23 parser.on('--exclusive', 'Manage SSH keys file exclusively.')
24 parser.on('--rotate-tokens', 'Force a rotation of all user tokens.')
25 parser.on('--skip-missing-users', "Don't try to create any local accounts.")
26 parser.on('--token-lifetime SECONDS', 'Create user tokens that expire after SECONDS.', Integer)
27 parser.on('--debug', 'Enable debug output')
28 end.parse!(into: options)
30 exclusive_banner = "#######################################################################################
31 # THIS FILE IS MANAGED BY #{$0} -- CHANGES WILL BE OVERWRITTEN #
32 #######################################################################################\n\n"
33 start_banner = "### BEGIN Arvados-managed keys -- changes between markers will be overwritten\n"
34 end_banner = "### END Arvados-managed keys -- changes between markers will be overwritten\n"
43 arv = Arvados.new({ :suppress_ssl_warnings => false })
44 logincluster_arv = Arvados.new({ :api_host => (ENV['LOGINCLUSTER_ARVADOS_API_HOST'] || ENV['ARVADOS_API_HOST']),
45 :api_token => (ENV['LOGINCLUSTER_ARVADOS_API_TOKEN'] || ENV['ARVADOS_API_TOKEN']),
46 :suppress_ssl_warnings => false })
48 vm_uuid = ENV['ARVADOS_VIRTUAL_MACHINE_UUID']
50 logins = arv.virtual_machine.logins(:uuid => vm_uuid)[:items]
51 logins = [] if logins.nil?
52 logins = logins.reject { |l| l[:username].nil? or l[:hostname].nil? or l[:virtual_machine_uuid] != vm_uuid }
56 open("/etc/login.defs", encoding: "utf-8") do |login_defs|
57 login_defs.each_line do |line|
58 next unless match = /^UID_MIN\s+(\S+)$/.match(line)
59 if match[1].start_with?("0x")
61 elsif match[1].start_with?("0")
66 new_uid_min = match[1].to_i(base)
67 uid_min = new_uid_min if (new_uid_min > 0)
73 if not pwnam[l[:username]]
75 pwnam[l[:username]] = Etc.getpwnam(l[:username])
77 if options[:"skip-missing-users"]
78 STDERR.puts "Account #{l[:username]} not found. Skipping"
82 if pwnam[l[:username]].uid < uid_min
83 STDERR.puts "Account #{l[:username]} uid #{pwnam[l[:username]].uid} < uid_min #{uid_min}. Skipping" if debug
93 STDERR.puts("Considering #{l[:username]} ...") if debug
94 keys[l[:username]] = Array.new() if not keys.has_key?(l[:username])
97 # Handle putty-style ssh public keys
98 key.sub!(/^(Comment: "r[^\n]*\n)(.*)$/m,'ssh-rsa \2 \1')
99 key.sub!(/^(Comment: "d[^\n]*\n)(.*)$/m,'ssh-dss \2 \1')
103 keys[l[:username]].push(key) if not keys[l[:username]].include?(key)
109 current_user_groups = Hash.new
110 while (ent = Etc.getgrent()) do
111 ent.mem.each do |member|
112 current_user_groups[member] ||= Array.new
113 current_user_groups[member].push ent.name
119 next if seen[l[:username]]
120 seen[l[:username]] = true
122 username = l[:username]
124 unless pwnam[l[:username]]
125 STDERR.puts "Creating account #{l[:username]}"
127 unless system("useradd", "-m",
131 STDERR.puts "Account creation failed for #{l[:username]}: #{$?}"
135 pwnam[username] = Etc.getpwnam(username)
137 STDERR.puts "Created account but then getpwnam() failed for #{l[:username]}: #{e}"
142 existing_groups = current_user_groups[username] || []
143 groups = l[:groups] || []
144 # Adding users to the FUSE group has long been hardcoded behavior.
147 groups.select! { |g| Etc.getgrnam(g) rescue false }
149 groups.each do |addgroup|
150 if existing_groups.index(addgroup).nil?
151 # User should be in group, but isn't, so add them.
152 STDERR.puts "Add user #{username} to #{addgroup} group"
153 system("usermod", "-aG", addgroup, username)
157 existing_groups.each do |removegroup|
158 if groups.index(removegroup).nil?
159 # User is in a group, but shouldn't be, so remove them.
160 STDERR.puts "Remove user #{username} from #{removegroup} group"
161 system("gpasswd", "-d", username, removegroup)
165 homedir = pwnam[l[:username]].dir
166 userdotssh = File.join(homedir, ".ssh")
167 Dir.mkdir(userdotssh) if !File.exist?(userdotssh)
169 newkeys = "###\n###\n" + keys[l[:username]].join("\n") + "\n###\n###\n"
171 keysfile = File.join(userdotssh, "authorized_keys")
173 if File.exist?(keysfile)
174 oldkeys = IO::read(keysfile)
179 if options[:exclusive]
180 newkeys = exclusive_banner + newkeys
181 elsif oldkeys.start_with?(exclusive_banner)
182 newkeys = start_banner + newkeys + end_banner
183 elsif (m = /^(.*?\n|)#{start_banner}(.*?\n|)#{end_banner}(.*)/m.match(oldkeys))
184 newkeys = m[1] + start_banner + newkeys + end_banner + m[3]
186 newkeys = start_banner + newkeys + end_banner + oldkeys
189 if oldkeys != newkeys then
190 f = File.new(keysfile, 'w')
195 userdotconfig = File.join(homedir, ".config")
196 if !File.exist?(userdotconfig)
197 Dir.mkdir(userdotconfig)
200 configarvados = File.join(userdotconfig, "arvados")
201 Dir.mkdir(configarvados) if !File.exist?(configarvados)
203 tokenfile = File.join(configarvados, "settings.conf")
206 STDERR.puts "Processing #{tokenfile} ..." if debug
208 if File.exist?(tokenfile)
209 # check if the token is still valid
210 myToken = ENV["ARVADOS_API_TOKEN"]
211 userEnv = IO::read(tokenfile)
212 if (m = /^ARVADOS_API_TOKEN=(.*?\n)/m.match(userEnv))
214 tmp_arv = Arvados.new({ :api_host => (ENV['LOGINCLUSTER_ARVADOS_API_HOST'] || ENV['ARVADOS_API_HOST']),
215 :api_token => (m[1]),
216 :suppress_ssl_warnings => false })
218 rescue Arvados::TransactionFailedError => e
219 if e.to_s =~ /401 Unauthorized/
220 STDERR.puts "Account #{l[:username]} token not valid, creating new token."
227 elsif !File.exist?(tokenfile) || options[:"rotate-tokens"]
228 STDERR.puts "Account #{l[:username]} token file not found, creating new token."
232 aca_params = {owner_uuid: l[:user_uuid], api_client_id: 0}
233 if options[:"token-lifetime"] && options[:"token-lifetime"] > 0
234 aca_params.merge!(expires_at: (Time.now + options[:"token-lifetime"]))
236 user_token = logincluster_arv.api_client_authorization.create(api_client_authorization: aca_params)
237 f = File.new(tokenfile, 'w')
238 f.write("ARVADOS_API_HOST=#{ENV['ARVADOS_API_HOST']}\n")
239 f.write("ARVADOS_API_TOKEN=v2/#{user_token[:uuid]}/#{user_token[:api_token]}\n")
243 STDERR.puts "Error setting token for #{l[:username]}: #{e}"
246 FileUtils.chown_R(l[:username], nil, userdotssh)
247 FileUtils.chown_R(l[:username], nil, userdotconfig)
248 File.chmod(0700, userdotssh)
249 File.chmod(0700, userdotconfig)
250 File.chmod(0700, configarvados)
251 File.chmod(0750, homedir)
252 File.chmod(0600, keysfile)
253 if File.exist?(tokenfile)
254 File.chmod(0600, tokenfile)
258 rescue Exception => bang
259 puts "Error: " + bang.to_s
260 puts bang.backtrace.join("\n")