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