Module: Dapp::Dapp::SshAgent

Included in:
Dapp::Dapp
Defined in:
lib/dapp/dapp/ssh_agent.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(_base) ⇒ Object



5
6
7
# File 'lib/dapp/dapp/ssh_agent.rb', line 5

def included(_base)
  ::Dapp::Dapp::Shellout::Base.default_env_keys << 'SSH_AUTH_SOCK'
end

Instance Method Details

#add_ssh_key(ssh_key_path) ⇒ Object



45
46
47
# File 'lib/dapp/dapp/ssh_agent.rb', line 45

def add_ssh_key(ssh_key_path)
  shellout! "ssh-add #{ssh_key_path}", env: { SSH_AUTH_SOCK: ssh_auth_sock(force_run_agent: true) }
end

#run_ssh_agentObject

<< self



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/dapp/dapp/ssh_agent.rb', line 10

def run_ssh_agent
  raise 'Cannot fork dapp process: there are active file locks' unless ::Dapp::Dimg::Lock::File.counter.zero?

  sock_name = "dapp-ssh-#{SecureRandom.uuid}"

  "/tmp/#{sock_name}".tap do |sock_path|
    Process.fork do
      Prctl.call(Prctl::PR_SET_PDEATHSIG, Signal.list['TERM'], 0, 0, 0)

      Process.setproctitle sock_name

      @ssh_agent_pid = nil

      Signal.trap('INT') {}
      Signal.trap('TERM') { Process.kill('TERM', @ssh_agent_pid) if @ssh_agent_pid }

      @ssh_agent_pid = Process.fork do
        STDOUT.reopen '/dev/null', 'a'
        STDERR.reopen '/dev/null', 'a'
        exec 'ssh-agent', '-d', '-a', sock_path
      end

      Process.wait @ssh_agent_pid
    end

    begin
      ::Timeout.timeout(10) do
        sleep 0.001 until File.exist? sock_path
      end
    rescue ::Timeout::Error
      raise Error::Dapp, code: :cannot_run_ssh_agent
    end
  end # sock_path
end

#setup_ssh_agentObject



62
63
64
65
66
67
68
69
70
71
# File 'lib/dapp/dapp/ssh_agent.rb', line 62

def setup_ssh_agent
  return unless options[:ssh_key]

  options[:ssh_key].each do |ssh_key|
    raise Error::Dapp, code: :ssh_key_not_found, data: { path: ssh_key } unless File.exist? ssh_key

    File.chmod 0o600, ssh_key
    add_ssh_key ssh_key
  end
end

#ssh_auth_sock(force_run_agent: false) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/dapp/dapp/ssh_agent.rb', line 49

def ssh_auth_sock(force_run_agent: false)
  @ssh_auth_sock ||= begin
    system_ssh_auth_sock = nil
    system_ssh_auth_sock = File.expand_path(ENV['SSH_AUTH_SOCK']) if ENV['SSH_AUTH_SOCK'] && File.exist?(ENV['SSH_AUTH_SOCK'])

    if force_run_agent
      run_ssh_agent.tap { |ssh_auth_sock| ENV['SSH_AUTH_SOCK'] = ssh_auth_sock }
    else
      system_ssh_auth_sock
    end
  end
end