20663: Improve permissions and ownership handling
[arvados.git] / services / login-sync / bin / arvados-login-sync
index 5c6691ab95279920498875a7e49295c8a2b4a5a4..a3150b8fd20a7d7edad9f2bd557c03d14aa0022c 100755 (executable)
@@ -12,6 +12,18 @@ require 'yaml'
 require 'optparse'
 require 'open3'
 
+def ensure_dir(path, mode, owner, group)
+  begin
+    Dir.mkdir(path, mode)
+  rescue Errno::EEXIST
+    # No change needed
+    false
+  else
+    FileUtils.chown(owner, group, path)
+    true
+  end
+end
+
 req_envs = %w(ARVADOS_API_HOST ARVADOS_API_TOKEN ARVADOS_VIRTUAL_MACHINE_UUID)
 req_envs.each do |k|
   unless ENV[k]
@@ -42,9 +54,14 @@ begin
     debug = true
   end
   arv = Arvados.new({ :suppress_ssl_warnings => false })
-  logincluster_arv = Arvados.new({ :api_host => (ENV['LOGINCLUSTER_ARVADOS_API_HOST'] || ENV['ARVADOS_API_HOST']),
-                                   :api_token => (ENV['LOGINCLUSTER_ARVADOS_API_TOKEN'] || ENV['ARVADOS_API_TOKEN']),
-                      :suppress_ssl_warnings => false })
+  logincluster_host = ENV['ARVADOS_API_HOST']
+  logincluster_name = arv.cluster_config['Login']['LoginCluster'] or ''
+
+  if logincluster_name != '' and logincluster_name != arv.cluster_config['ClusterID']
+    logincluster_host = arv.cluster_config['RemoteClusters'][logincluster_name]['Host']
+  end
+  logincluster_arv = Arvados.new({ :api_host => logincluster_host,
+                                   :suppress_ssl_warnings => false })
 
   vm_uuid = ENV['ARVADOS_VIRTUAL_MACHINE_UUID']
 
@@ -141,6 +158,13 @@ begin
       end
     end
 
+    user_gid = pwnam[username].gid
+    homedir = pwnam[l[:username]].dir
+    if !File.exist?(homedir)
+      STDERR.puts "Cannot set up user #{username} because their home directory #{homedir} does not exist. Skipping."
+      next
+    end
+
     existing_groups = current_user_groups[username] || []
     groups = l[:groups] || []
     # Adding users to the FUSE group has long been hardcoded behavior.
@@ -170,17 +194,15 @@ begin
       end
     end
 
-    homedir = pwnam[l[:username]].dir
     userdotssh = File.join(homedir, ".ssh")
-    Dir.mkdir(userdotssh) if !File.exist?(userdotssh)
+    ensure_dir(userdotssh, 0700, username, user_gid)
 
     newkeys = "###\n###\n" + keys[l[:username]].join("\n") + "\n###\n###\n"
 
     keysfile = File.join(userdotssh, "authorized_keys")
-
-    if File.exist?(keysfile)
-      oldkeys = IO::read(keysfile)
-    else
+    begin
+      oldkeys = File.read(keysfile)
+    rescue Errno::ENOENT
       oldkeys = ""
     end
 
@@ -195,18 +217,16 @@ begin
     end
 
     if oldkeys != newkeys then
-      f = File.new(keysfile, 'w')
-      f.write(newkeys)
-      f.close()
+      File.open(keysfile, 'w', 0600) do |f|
+        f.write(newkeys)
+      end
+      FileUtils.chown(username, user_gid, keysfile)
     end
 
     userdotconfig = File.join(homedir, ".config")
-    if !File.exist?(userdotconfig)
-      Dir.mkdir(userdotconfig)
-    end
-
+    ensure_dir(userdotconfig, 0755, username, user_gid)
     configarvados = File.join(userdotconfig, "arvados")
-    Dir.mkdir(configarvados) if !File.exist?(configarvados)
+    ensure_dir(configarvados, 0700, username, user_gid)
 
     tokenfile = File.join(configarvados, "settings.conf")
 
@@ -216,12 +236,12 @@ begin
       if File.exist?(tokenfile)
         # check if the token is still valid
         myToken = ENV["ARVADOS_API_TOKEN"]
-        userEnv = IO::read(tokenfile)
+        userEnv = File.read(tokenfile)
         if (m = /^ARVADOS_API_TOKEN=(.*?\n)/m.match(userEnv))
           begin
-            tmp_arv = Arvados.new({ :api_host => (ENV['LOGINCLUSTER_ARVADOS_API_HOST'] || ENV['ARVADOS_API_HOST']),
-                                   :api_token => (m[1]),
-                      :suppress_ssl_warnings => false })
+            tmp_arv = Arvados.new({ :api_host => logincluster_host,
+                                    :api_token => (m[1]),
+                                    :suppress_ssl_warnings => false })
             tmp_arv.user.current
           rescue Arvados::TransactionFailedError => e
             if e.to_s =~ /401 Unauthorized/
@@ -242,25 +262,15 @@ begin
           aca_params.merge!(expires_at: (Time.now + options[:"token-lifetime"]))
         end
         user_token = logincluster_arv.api_client_authorization.create(api_client_authorization: aca_params)
-        f = File.new(tokenfile, 'w')
-        f.write("ARVADOS_API_HOST=#{ENV['ARVADOS_API_HOST']}\n")
-        f.write("ARVADOS_API_TOKEN=v2/#{user_token[:uuid]}/#{user_token[:api_token]}\n")
-        f.close()
+        File.open(tokenfile, 'w', 0600) do |f|
+          f.write("ARVADOS_API_HOST=#{ENV['ARVADOS_API_HOST']}\n")
+          f.write("ARVADOS_API_TOKEN=v2/#{user_token[:uuid]}/#{user_token[:api_token]}\n")
+        end
+        FileUtils.chown(username, user_gid, tokenfile)
       end
     rescue => e
       STDERR.puts "Error setting token for #{l[:username]}: #{e}"
     end
-
-    FileUtils.chown_R(l[:username], nil, userdotssh)
-    FileUtils.chown_R(l[:username], nil, userdotconfig)
-    File.chmod(0700, userdotssh)
-    File.chmod(0700, userdotconfig)
-    File.chmod(0700, configarvados)
-    File.chmod(0750, homedir)
-    File.chmod(0600, keysfile)
-    if File.exist?(tokenfile)
-      File.chmod(0600, tokenfile)
-    end
   end
 
 rescue Exception => bang