Skip to content

Commit

Permalink
Allow override of public ip, open for someone else (#11)
Browse files Browse the repository at this point in the history
* Allow override of public ip, open for someone else

    Sparoid.auth(.., open_for_ip:)

Useful when Sparoid.auth operation isn't done on the instance that will
connect, e.g. web server letting a browser accessing a host.

Performance detail, passing an `Resolv::IPv4` object to `Resolv::IPv4.create`
will just trigger early return, so it's fast.
  • Loading branch information
jage authored Mar 3, 2023
1 parent 33d1125 commit 9745d07
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/sparoid.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ module Sparoid # rubocop:disable Metrics/ModuleLength
SPAROID_CACHE_PATH = ENV.fetch("SPAROID_CACHE_PATH", "/tmp/.sparoid_public_ip")

# Send an authorization packet
def auth(key, hmac_key, host, port)
def auth(key, hmac_key, host, port, open_for_ip: cached_public_ip)
addrs = resolve_ip_addresses(host, port)

msg = message(cached_public_ip)
ip = Resolv::IPv4.create(open_for_ip)
msg = message(ip)
data = prefix_hmac(hmac_key, encrypt(key, msg))
sendmsg(addrs, data)

Expand Down
13 changes: 13 additions & 0 deletions test/sparoid_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,19 @@ def test_it_sends_message
end
end

def test_it_opens_for_passed_in_ip_argument
key = "0000000000000000000000000000000000000000000000000000000000000000"
hmac_key = "0000000000000000000000000000000000000000000000000000000000000000"
UDPSocket.open do |server|
server.bind("127.0.0.1", 0)
port = server.addr[1]
s = Sparoid::Instance.new
s.stub(:public_ip, ->(*_) { raise "public_ip method not expected to be called" }) do
s.auth(key, hmac_key, "127.0.0.1", port, open_for_ip: "127.0.1.1")
end
end
end

def test_it_sends_message_with_empty_cache_file
Sparoid.stub_const(:SPAROID_CACHE_PATH, Tempfile.new.path) do
assert_output(nil, "") { test_it_sends_message }
Expand Down

0 comments on commit 9745d07

Please sign in to comment.