Fix 2.4.2 upgrade notes formatting refs #19330
[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 req_envs = %w(ARVADOS_API_HOST ARVADOS_API_TOKEN ARVADOS_VIRTUAL_MACHINE_UUID)
16 req_envs.each do |k|
17   unless ENV[k]
18     abort "Fatal: These environment vars must be set: #{req_envs}"
19   end
20 end
21
22 options = {}
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)
30
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"
36
37 keys = ''
38
39 begin
40   debug = false
41   if options[:"debug"]
42     debug = true
43   end
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 })
48
49   vm_uuid = ENV['ARVADOS_VIRTUAL_MACHINE_UUID']
50
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 }
54
55   # No system users
56   uid_min = 1000
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")
61         base = 16
62       elsif match[1].start_with?("0")
63         base = 8
64       else
65         base = 10
66       end
67       new_uid_min = match[1].to_i(base)
68       uid_min = new_uid_min if (new_uid_min > 0)
69     end
70   end
71
72   pwnam = Hash.new()
73   logins.reject! do |l|
74     if not pwnam[l[:username]]
75       begin
76         pwnam[l[:username]] = Etc.getpwnam(l[:username])
77       rescue
78         if options[:"skip-missing-users"]
79           STDERR.puts "Account #{l[:username]} not found. Skipping"
80           true
81         end
82       else
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
85           true
86         end
87       end
88     end
89   end
90   keys = Hash.new()
91
92   # Collect all keys
93   logins.each do |l|
94     STDERR.puts("Considering #{l[:username]} ...") if debug
95     keys[l[:username]] = Array.new() if not keys.has_key?(l[:username])
96     key = l[:public_key]
97     if !key.nil?
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')
101       key.gsub!(/\n/,'')
102       key.strip
103
104       keys[l[:username]].push(key) if not keys[l[:username]].include?(key)
105     end
106   end
107
108   seen = Hash.new()
109
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
115     end
116   end
117   Etc.endgrent()
118
119   logins.each do |l|
120     next if seen[l[:username]]
121     seen[l[:username]] = true
122
123     username = l[:username]
124
125     unless pwnam[l[:username]]
126       STDERR.puts "Creating account #{l[:username]}"
127       # Create new user
128       out, st = Open3.capture2e("useradd", "-m",
129                 "-c", username,
130                 "-s", "/bin/bash",
131                 username)
132       if st.exitstatus != 0
133         STDERR.puts "Account creation failed for #{l[:username]}:\n#{out}"
134         next
135       end
136       begin
137         pwnam[username] = Etc.getpwnam(username)
138       rescue => e
139         STDERR.puts "Created account but then getpwnam() failed for #{l[:username]}: #{e}"
140         raise
141       end
142     end
143
144     existing_groups = current_user_groups[username] || []
145     groups = l[:groups] || []
146     # Adding users to the FUSE group has long been hardcoded behavior.
147     groups << "fuse"
148     groups << username
149     groups.select! { |g| Etc.getgrnam(g) rescue false }
150
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}"
158         end
159       end
160     end
161
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}"
169         end
170       end
171     end
172
173     homedir = pwnam[l[:username]].dir
174     userdotssh = File.join(homedir, ".ssh")
175     Dir.mkdir(userdotssh) if !File.exist?(userdotssh)
176
177     newkeys = "###\n###\n" + keys[l[:username]].join("\n") + "\n###\n###\n"
178
179     keysfile = File.join(userdotssh, "authorized_keys")
180
181     if File.exist?(keysfile)
182       oldkeys = IO::read(keysfile)
183     else
184       oldkeys = ""
185     end
186
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]
193     else
194       newkeys = start_banner + newkeys + end_banner + oldkeys
195     end
196
197     if oldkeys != newkeys then
198       f = File.new(keysfile, 'w')
199       f.write(newkeys)
200       f.close()
201     end
202
203     userdotconfig = File.join(homedir, ".config")
204     if !File.exist?(userdotconfig)
205       Dir.mkdir(userdotconfig)
206     end
207
208     configarvados = File.join(userdotconfig, "arvados")
209     Dir.mkdir(configarvados) if !File.exist?(configarvados)
210
211     tokenfile = File.join(configarvados, "settings.conf")
212
213     begin
214       STDERR.puts "Processing #{tokenfile} ..." if debug
215       newToken = false
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))
221           begin
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 })
225             tmp_arv.user.current
226           rescue Arvados::TransactionFailedError => e
227             if e.to_s =~ /401 Unauthorized/
228               STDERR.puts "Account #{l[:username]} token not valid, creating new token."
229               newToken = true
230             else
231               raise
232             end
233           end
234         end
235       elsif !File.exist?(tokenfile) || options[:"rotate-tokens"]
236         STDERR.puts "Account #{l[:username]} token file not found, creating new token."
237         newToken = true
238       end
239       if newToken
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"]))
243         end
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")
248         f.close()
249       end
250     rescue => e
251       STDERR.puts "Error setting token for #{l[:username]}: #{e}"
252     end
253
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)
263     end
264   end
265
266 rescue Exception => bang
267   puts "Error: " + bang.to_s
268   puts bang.backtrace.join("\n")
269   exit 1
270 end