Sha256: b97ffb780b365c8480b5d1d525142858ddb02afa1f71e0ec757864c15cccf069

Contents?: true

Size: 1.24 KB

Versions: 5

Compression:

Stored size: 1.24 KB

Contents

# frozen_string_literal: true

require "fusuma/custom_process"
require "etc"

module Fusuma
  module Plugin
    module Appmatcher
      # Drop sudo privileges
      module UserSwitcher
        include CustomProcess

        # Drops privileges to that of the specified user
        def drop_priv(user)
          # Process.initgroups(user.username, user.gid)
          Process::Sys.setegid(user.gid)
          Process::Sys.setgid(user.gid)
          Process::Sys.setuid(user.uid)
        end

        # Execute the provided block in a child process as the specified user
        # The parent blocks until the child finishes.
        def as_user(user = login_user, proctitle:)
          self.proctitle = "#{self.class.name.underscore}(#{user.username}) -> #{proctitle}"

          fork do
            drop_priv(user)
            yield(user) if block_given?
          end
        end

        User = Struct.new(:username, :uid, :gid)
        def login_user
          @login_user ||= begin
            username = ENV["SUDO_USER"] || Etc.getlogin
            uid = `id -u #{username}`.chomp.to_i
            gid = `id -g #{username}`.chomp.to_i
            User.new(username, uid, gid)
          end
        end
        module_function :login_user
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
fusuma-plugin-appmatcher-0.7.1 lib/fusuma/plugin/appmatcher/user_switcher.rb
fusuma-plugin-appmatcher-0.7.0 lib/fusuma/plugin/appmatcher/user_switcher.rb
fusuma-plugin-appmatcher-0.6.1 lib/fusuma/plugin/appmatcher/user_switcher.rb
fusuma-plugin-appmatcher-0.6.0 lib/fusuma/plugin/appmatcher/user_switcher.rb
fusuma-plugin-appmatcher-0.5.0 lib/fusuma/plugin/appmatcher/user_switcher.rb