20259: Add documentation for banner and tooltip features
[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_host = ENV['ARVADOS_API_HOST']
46   logincluster_name = arv.cluster_config['Login']['LoginCluster'] or ''
47
48   if logincluster_name != '' and logincluster_name != arv.cluster_config['ClusterID']
49     logincluster_host = arv.cluster_config['RemoteClusters'][logincluster_name]['Host']
50   end
51   logincluster_arv = Arvados.new({ :api_host => logincluster_host,
52                                    :suppress_ssl_warnings => false })
53
54   vm_uuid = ENV['ARVADOS_VIRTUAL_MACHINE_UUID']
55
56   logins = arv.virtual_machine.logins(:uuid => vm_uuid)[:items]
57   logins = [] if logins.nil?
58   logins = logins.reject { |l| l[:username].nil? or l[:hostname].nil? or l[:virtual_machine_uuid] != vm_uuid }
59
60   # No system users
61   uid_min = 1000
62   open("/etc/login.defs", encoding: "utf-8") do |login_defs|
63     login_defs.each_line do |line|
64       next unless match = /^UID_MIN\s+(\S+)$/.match(line)
65       if match[1].start_with?("0x")
66         base = 16
67       elsif match[1].start_with?("0")
68         base = 8
69       else
70         base = 10
71       end
72       new_uid_min = match[1].to_i(base)
73       uid_min = new_uid_min if (new_uid_min > 0)
74     end
75   end
76
77   pwnam = Hash.new()
78   logins.reject! do |l|
79     if not pwnam[l[:username]]
80       begin
81         pwnam[l[:username]] = Etc.getpwnam(l[:username])
82       rescue
83         if options[:"skip-missing-users"]
84           STDERR.puts "Account #{l[:username]} not found. Skipping"
85           true
86         end
87       else
88         if pwnam[l[:username]].uid < uid_min
89           STDERR.puts "Account #{l[:username]} uid #{pwnam[l[:username]].uid} < uid_min #{uid_min}. Skipping" if debug
90           true
91         end
92       end
93     end
94   end
95   keys = Hash.new()
96
97   # Collect all keys
98   logins.each do |l|
99     STDERR.puts("Considering #{l[:username]} ...") if debug
100     keys[l[:username]] = Array.new() if not keys.has_key?(l[:username])
101     key = l[:public_key]
102     if !key.nil?
103       # Handle putty-style ssh public keys
104       key.sub!(/^(Comment: "r[^\n]*\n)(.*)$/m,'ssh-rsa \2 \1')
105       key.sub!(/^(Comment: "d[^\n]*\n)(.*)$/m,'ssh-dss \2 \1')
106       key.gsub!(/\n/,'')
107       key.strip
108
109       keys[l[:username]].push(key) if not keys[l[:username]].include?(key)
110     end
111   end
112
113   seen = Hash.new()
114
115   current_user_groups = Hash.new
116   while (ent = Etc.getgrent()) do
117     ent.mem.each do |member|
118       current_user_groups[member] ||= Array.new
119       current_user_groups[member].push ent.name
120     end
121   end
122   Etc.endgrent()
123
124   logins.each do |l|
125     next if seen[l[:username]]
126     seen[l[:username]] = true
127
128     username = l[:username]
129
130     unless pwnam[l[:username]]
131       STDERR.puts "Creating account #{l[:username]}"
132       # Create new user
133       out, st = Open3.capture2e("useradd", "-m",
134                 "-c", username,
135                 "-s", "/bin/bash",
136                 username)
137       if st.exitstatus != 0
138         STDERR.puts "Account creation failed for #{l[:username]}:\n#{out}"
139         next
140       end
141       begin
142         pwnam[username] = Etc.getpwnam(username)
143       rescue => e
144         STDERR.puts "Created account but then getpwnam() failed for #{l[:username]}: #{e}"
145         raise
146       end
147     end
148
149     existing_groups = current_user_groups[username] || []
150     groups = l[:groups] || []
151     # Adding users to the FUSE group has long been hardcoded behavior.
152     groups << "fuse"
153     groups << username
154     groups.select! { |g| Etc.getgrnam(g) rescue false }
155
156     groups.each do |addgroup|
157       if existing_groups.index(addgroup).nil?
158         # User should be in group, but isn't, so add them.
159         STDERR.puts "Add user #{username} to #{addgroup} group"
160         out, st = Open3.capture2e("usermod", "-aG", addgroup, username)
161         if st.exitstatus != 0
162           STDERR.puts "Failed to add #{username} to #{addgroup} group:\n#{out}"
163         end
164       end
165     end
166
167     existing_groups.each do |removegroup|
168       if groups.index(removegroup).nil?
169         # User is in a group, but shouldn't be, so remove them.
170         STDERR.puts "Remove user #{username} from #{removegroup} group"
171         out, st = Open3.capture2e("gpasswd", "-d", username, removegroup)
172         if st.exitstatus != 0
173           STDERR.puts "Failed to remove user #{username} from #{removegroup} group:\n#{out}"
174         end
175       end
176     end
177
178     homedir = pwnam[l[:username]].dir
179     userdotssh = File.join(homedir, ".ssh")
180     Dir.mkdir(userdotssh) if !File.exist?(userdotssh)
181
182     newkeys = "###\n###\n" + keys[l[:username]].join("\n") + "\n###\n###\n"
183
184     keysfile = File.join(userdotssh, "authorized_keys")
185
186     if File.exist?(keysfile)
187       oldkeys = IO::read(keysfile)
188     else
189       oldkeys = ""
190     end
191
192     if options[:exclusive]
193       newkeys = exclusive_banner + newkeys
194     elsif oldkeys.start_with?(exclusive_banner)
195       newkeys = start_banner + newkeys + end_banner
196     elsif (m = /^(.*?\n|)#{start_banner}(.*?\n|)#{end_banner}(.*)/m.match(oldkeys))
197       newkeys = m[1] + start_banner + newkeys + end_banner + m[3]
198     else
199       newkeys = start_banner + newkeys + end_banner + oldkeys
200     end
201
202     if oldkeys != newkeys then
203       f = File.new(keysfile, 'w')
204       f.write(newkeys)
205       f.close()
206     end
207
208     userdotconfig = File.join(homedir, ".config")
209     if !File.exist?(userdotconfig)
210       Dir.mkdir(userdotconfig)
211     end
212
213     configarvados = File.join(userdotconfig, "arvados")
214     Dir.mkdir(configarvados) if !File.exist?(configarvados)
215
216     tokenfile = File.join(configarvados, "settings.conf")
217
218     begin
219       STDERR.puts "Processing #{tokenfile} ..." if debug
220       newToken = false
221       if File.exist?(tokenfile)
222         # check if the token is still valid
223         myToken = ENV["ARVADOS_API_TOKEN"]
224         userEnv = IO::read(tokenfile)
225         if (m = /^ARVADOS_API_TOKEN=(.*?\n)/m.match(userEnv))
226           begin
227             tmp_arv = Arvados.new({ :api_host => logincluster_host,
228                                     :api_token => (m[1]),
229                                     :suppress_ssl_warnings => false })
230             tmp_arv.user.current
231           rescue Arvados::TransactionFailedError => e
232             if e.to_s =~ /401 Unauthorized/
233               STDERR.puts "Account #{l[:username]} token not valid, creating new token."
234               newToken = true
235             else
236               raise
237             end
238           end
239         end
240       elsif !File.exist?(tokenfile) || options[:"rotate-tokens"]
241         STDERR.puts "Account #{l[:username]} token file not found, creating new token."
242         newToken = true
243       end
244       if newToken
245         aca_params = {owner_uuid: l[:user_uuid], api_client_id: 0}
246         if options[:"token-lifetime"] && options[:"token-lifetime"] > 0
247           aca_params.merge!(expires_at: (Time.now + options[:"token-lifetime"]))
248         end
249         user_token = logincluster_arv.api_client_authorization.create(api_client_authorization: aca_params)
250         f = File.new(tokenfile, 'w')
251         f.write("ARVADOS_API_HOST=#{ENV['ARVADOS_API_HOST']}\n")
252         f.write("ARVADOS_API_TOKEN=v2/#{user_token[:uuid]}/#{user_token[:api_token]}\n")
253         f.close()
254       end
255     rescue => e
256       STDERR.puts "Error setting token for #{l[:username]}: #{e}"
257     end
258
259     FileUtils.chown_R(l[:username], nil, userdotssh)
260     FileUtils.chown_R(l[:username], nil, userdotconfig)
261     File.chmod(0700, userdotssh)
262     File.chmod(0700, userdotconfig)
263     File.chmod(0700, configarvados)
264     File.chmod(0750, homedir)
265     File.chmod(0600, keysfile)
266     if File.exist?(tokenfile)
267       File.chmod(0600, tokenfile)
268     end
269   end
270
271 rescue Exception => bang
272   puts "Error: " + bang.to_s
273   puts bang.backtrace.join("\n")
274   exit 1
275 end