da8a21efa37c8a8db91b925bc56040f7bff494b8
[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
14 req_envs = %w(ARVADOS_API_HOST ARVADOS_API_TOKEN ARVADOS_VIRTUAL_MACHINE_UUID)
15 req_envs.each do |k|
16   unless ENV[k]
17     abort "Fatal: These environment vars must be set: #{req_envs}"
18   end
19 end
20
21 options = {}
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)
29
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"
35
36 keys = ''
37
38 begin
39   debug = false
40   if options[:"debug"]
41     debug = true
42   end
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 })
47
48   vm_uuid = ENV['ARVADOS_VIRTUAL_MACHINE_UUID']
49
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 }
53
54   # No system users
55   uid_min = 1000
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")
60         base = 16
61       elsif match[1].start_with?("0")
62         base = 8
63       else
64         base = 10
65       end
66       new_uid_min = match[1].to_i(base)
67       uid_min = new_uid_min if (new_uid_min > 0)
68     end
69   end
70
71   pwnam = Hash.new()
72   logins.reject! do |l|
73     if not pwnam[l[:username]]
74       begin
75         pwnam[l[:username]] = Etc.getpwnam(l[:username])
76       rescue
77         if options[:"skip-missing-users"]
78           STDERR.puts "Account #{l[:username]} not found. Skipping"
79           true
80         end
81       else
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
84           true
85         end
86       end
87     end
88   end
89   keys = Hash.new()
90
91   # Collect all keys
92   logins.each do |l|
93     STDERR.puts("Considering #{l[:username]} ...") if debug
94     keys[l[:username]] = Array.new() if not keys.has_key?(l[:username])
95     key = l[:public_key]
96     if !key.nil?
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')
100       key.gsub!(/\n/,'')
101       key.strip
102
103       keys[l[:username]].push(key) if not keys[l[:username]].include?(key)
104     end
105   end
106
107   seen = Hash.new()
108
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
114     end
115   end
116   Etc.endgrent()
117
118   logins.each do |l|
119     next if seen[l[:username]]
120     seen[l[:username]] = true
121
122     username = l[:username]
123
124     unless pwnam[l[:username]]
125       STDERR.puts "Creating account #{l[:username]}"
126       # Create new user
127       unless system("useradd", "-m",
128                 "-c", username,
129                 "-s", "/bin/bash",
130                 username)
131         STDERR.puts "Account creation failed for #{l[:username]}: #{$?}"
132         next
133       end
134       begin
135         pwnam[username] = Etc.getpwnam(username)
136       rescue => e
137         STDERR.puts "Created account but then getpwnam() failed for #{l[:username]}: #{e}"
138         raise
139       end
140     end
141
142     existing_groups = current_user_groups[username] || []
143     groups = l[:groups] || []
144     # Adding users to the FUSE group has long been hardcoded behavior.
145     groups << "fuse"
146     groups << username
147     groups.select! { |g| Etc.getgrnam(g) rescue false }
148
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)
154       end
155     end
156
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)
162       end
163     end
164
165     homedir = pwnam[l[:username]].dir
166     userdotssh = File.join(homedir, ".ssh")
167     Dir.mkdir(userdotssh) if !File.exist?(userdotssh)
168
169     newkeys = "###\n###\n" + keys[l[:username]].join("\n") + "\n###\n###\n"
170
171     keysfile = File.join(userdotssh, "authorized_keys")
172
173     if File.exist?(keysfile)
174       oldkeys = IO::read(keysfile)
175     else
176       oldkeys = ""
177     end
178
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]
185     else
186       newkeys = start_banner + newkeys + end_banner + oldkeys
187     end
188
189     if oldkeys != newkeys then
190       f = File.new(keysfile, 'w')
191       f.write(newkeys)
192       f.close()
193     end
194
195     userdotconfig = File.join(homedir, ".config")
196     if !File.exist?(userdotconfig)
197       Dir.mkdir(userdotconfig)
198     end
199
200     configarvados = File.join(userdotconfig, "arvados")
201     Dir.mkdir(configarvados) if !File.exist?(configarvados)
202
203     tokenfile = File.join(configarvados, "settings.conf")
204
205     begin
206       STDERR.puts "Processing #{tokenfile} ..." if debug
207       newToken = false
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))
213           begin
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 })
217             tmp_arv.user.current
218           rescue Arvados::TransactionFailedError => e
219             if e.to_s =~ /401 Unauthorized/
220               STDERR.puts "Account #{l[:username]} token not valid, creating new token."
221               newToken = true
222             else
223               raise
224             end
225           end
226         end
227       elsif !File.exist?(tokenfile) || options[:"rotate-tokens"]
228         STDERR.puts "Account #{l[:username]} token file not found, creating new token."
229         newToken = true
230       end
231       if newToken
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"]))
235         end
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")
240         f.close()
241       end
242     rescue => e
243       STDERR.puts "Error setting token for #{l[:username]}: #{e}"
244     end
245
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)
255     end
256   end
257
258 rescue Exception => bang
259   puts "Error: " + bang.to_s
260   puts bang.backtrace.join("\n")
261   exit 1
262 end