a9bff05464740d804ed3b1f5827c757740c97187
[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
13 req_envs = %w(ARVADOS_API_HOST ARVADOS_API_TOKEN ARVADOS_VIRTUAL_MACHINE_UUID)
14 req_envs.each do |k|
15   unless ENV[k]
16     abort "Fatal: These environment vars must be set: #{req_envs}"
17   end
18 end
19
20 exclusive_mode = ARGV.index("--exclusive")
21 exclusive_banner = "#######################################################################################
22 #  THIS FILE IS MANAGED BY #{$0} -- CHANGES WILL BE OVERWRITTEN  #
23 #######################################################################################\n\n"
24 start_banner = "### BEGIN Arvados-managed keys -- changes between markers will be overwritten\n"
25 end_banner = "### END Arvados-managed keys -- changes between markers will be overwritten\n"
26
27 # Don't try to create any local accounts
28 skip_missing_users = ARGV.index("--skip-missing-users")
29
30 keys = ''
31
32 begin
33   arv = Arvados.new({ :suppress_ssl_warnings => false })
34   logincluster_arv = Arvados.new({ :api_host => (ENV['LOGINCLUSTER_ARVADOS_API_HOST'] || ENV['ARVADOS_API_HOST']),
35                                    :api_token => (ENV['LOGINCLUSTER_ARVADOS_API_TOKEN'] || ENV['ARVADOS_API_TOKEN']),
36                       :suppress_ssl_warnings => false })
37
38   vm_uuid = ENV['ARVADOS_VIRTUAL_MACHINE_UUID']
39
40   logins = arv.virtual_machine.logins(:uuid => vm_uuid)[:items]
41   logins = [] if logins.nil?
42   logins = logins.reject { |l| l[:username].nil? or l[:hostname].nil? or l[:virtual_machine_uuid] != vm_uuid }
43
44   # No system users
45   uid_min = 1000
46   open("/etc/login.defs", encoding: "utf-8") do |login_defs|
47     login_defs.each_line do |line|
48       next unless match = /^UID_MIN\s+(\S+)$/.match(line)
49       if match[1].start_with?("0x")
50         base = 16
51       elsif match[1].start_with?("0")
52         base = 8
53       else
54         base = 10
55       end
56       new_uid_min = match[1].to_i(base)
57       uid_min = new_uid_min if (new_uid_min > 0)
58     end
59   end
60
61   pwnam = Hash.new()
62   logins.reject! do |l|
63     if not pwnam[l[:username]]
64       begin
65         pwnam[l[:username]] = Etc.getpwnam(l[:username])
66       rescue
67         if skip_missing_users
68           STDERR.puts "Account #{l[:username]} not found. Skipping"
69           true
70         end
71       else
72         if pwnam[l[:username]].uid < uid_min
73           STDERR.puts "Account #{l[:username]} uid #{pwnam[l[:username]].uid} < uid_min #{uid_min}. Skipping"
74           true
75         end
76       end
77     end
78   end
79   keys = Hash.new()
80
81   # Collect all keys
82   logins.each do |l|
83     keys[l[:username]] = Array.new() if not keys.has_key?(l[:username])
84     key = l[:public_key]
85     if !key.nil?
86       # Handle putty-style ssh public keys
87       key.sub!(/^(Comment: "r[^\n]*\n)(.*)$/m,'ssh-rsa \2 \1')
88       key.sub!(/^(Comment: "d[^\n]*\n)(.*)$/m,'ssh-dss \2 \1')
89       key.gsub!(/\n/,'')
90       key.strip
91
92       keys[l[:username]].push(key) if not keys[l[:username]].include?(key)
93     end
94   end
95
96   seen = Hash.new()
97
98   current_user_groups = Hash.new
99   while (ent = Etc.getgrent()) do
100     ent.mem.each do |member|
101       current_user_groups[member] ||= Array.new
102       current_user_groups[member].push ent.name
103     end
104   end
105   Etc.endgrent()
106
107   logins.each do |l|
108     next if seen[l[:username]]
109     seen[l[:username]] = true
110
111     username = l[:username]
112
113     unless pwnam[l[:username]]
114       STDERR.puts "Creating account #{l[:username]}"
115       # Create new user
116       unless system("useradd", "-m",
117                 "-c", username,
118                 "-s", "/bin/bash",
119                 username)
120         STDERR.puts "Account creation failed for #{l[:username]}: #{$?}"
121         next
122       end
123       begin
124         pwnam[username] = Etc.getpwnam(username)
125       rescue => e
126         STDERR.puts "Created account but then getpwnam() failed for #{l[:username]}: #{e}"
127         raise
128       end
129     end
130
131     existing_groups = current_user_groups[username] || []
132     groups = l[:groups] || []
133     # Adding users to the FUSE group has long been hardcoded behavior.
134     groups << "fuse"
135     groups << username
136     groups.select! { |g| Etc.getgrnam(g) rescue false }
137
138     groups.each do |addgroup|
139       if existing_groups.index(addgroup).nil?
140         # User should be in group, but isn't, so add them.
141         STDERR.puts "Add user #{username} to #{addgroup} group"
142         system("adduser", username, addgroup)
143       end
144     end
145
146     existing_groups.each do |removegroup|
147       if groups.index(removegroup).nil?
148         # User is in a group, but shouldn't be, so remove them.
149         STDERR.puts "Remove user #{username} from #{removegroup} group"
150         system("deluser", username, removegroup)
151       end
152     end
153
154     homedir = pwnam[l[:username]].dir
155     userdotssh = File.join(homedir, ".ssh")
156     Dir.mkdir(userdotssh) if !File.exist?(userdotssh)
157
158     newkeys = "###\n###\n" + keys[l[:username]].join("\n") + "\n###\n###\n"
159
160     keysfile = File.join(userdotssh, "authorized_keys")
161
162     if File.exist?(keysfile)
163       oldkeys = IO::read(keysfile)
164     else
165       oldkeys = ""
166     end
167
168     if exclusive_mode
169       newkeys = exclusive_banner + newkeys
170     elsif oldkeys.start_with?(exclusive_banner)
171       newkeys = start_banner + newkeys + end_banner
172     elsif (m = /^(.*?\n|)#{start_banner}(.*?\n|)#{end_banner}(.*)/m.match(oldkeys))
173       newkeys = m[1] + start_banner + newkeys + end_banner + m[3]
174     else
175       newkeys = start_banner + newkeys + end_banner + oldkeys
176     end
177
178     if oldkeys != newkeys then
179       f = File.new(keysfile, 'w')
180       f.write(newkeys)
181       f.close()
182     end
183
184     userdotconfig = File.join(homedir, ".config")
185     if !File.exist?(userdotconfig)
186       Dir.mkdir(userdotconfig)
187     end
188
189     configarvados = File.join(userdotconfig, "arvados")
190     Dir.mkdir(configarvados) if !File.exist?(configarvados)
191
192     tokenfile = File.join(configarvados, "settings.conf")
193
194     begin
195       if !File.exist?(tokenfile)
196         user_token = logincluster_arv.api_client_authorization.create(api_client_authorization: {owner_uuid: l[:user_uuid], api_client_id: 0})
197         f = File.new(tokenfile, 'w')
198         f.write("ARVADOS_API_HOST=#{ENV['ARVADOS_API_HOST']}\n")
199         f.write("ARVADOS_API_TOKEN=v2/#{user_token[:uuid]}/#{user_token[:api_token]}\n")
200         f.close()
201       end
202     rescue => e
203       STDERR.puts "Error setting token for #{l[:username]}: #{e}"
204     end
205
206     FileUtils.chown_R(l[:username], nil, userdotssh)
207     FileUtils.chown_R(l[:username], nil, userdotconfig)
208     File.chmod(0700, userdotssh)
209     File.chmod(0700, userdotconfig)
210     File.chmod(0700, configarvados)
211     File.chmod(0750, homedir)
212     File.chmod(0600, keysfile)
213     if File.exist?(tokenfile)
214       File.chmod(0600, tokenfile)
215     end
216   end
217
218 rescue Exception => bang
219   puts "Error: " + bang.to_s
220   puts bang.backtrace.join("\n")
221   exit 1
222 end