3

I'm writing unit tests for a Node.js Express server. The server does some stuff that depends on the remote client's IP address, retrieved using req.ip on the server.

How can I write unit tests that will spoof their own IP addresses to test the server's responses, or is there a better way to achieve the same end? (I'm writing the unit tests in jasmine-node, if it matters.)

jab
  • 4,053
  • 3
  • 33
  • 40

1 Answers1

2

You can use the trust proxy feature of express to fake requests from ip addresses for your tests. When you enable trust proxy in express by app.enable('trust proxy') you can add the X-Forwarded-ForHTTP header and set it's value to the ip required by the test.

The express ip/trust proxy behavior is documented here

saintedlama
  • 6,838
  • 1
  • 28
  • 46
  • Is that a behavior I generally want to enable on my server? – jab May 23 '13 at 16:49
  • If you have a proxy before your express app, yes. Otherwise definitely no because clients could spoof an ip address by setting the X-Forwarded-For header – saintedlama May 24 '13 at 05:12
  • Hmm, I'd really like a solution that doesn't make my server vulnerable. I'm just using IP addresses as a fallback way to do localization, but still. I suppose I could send a testing IP in a made-up HTTP header that a hacker is unlikely to stumble upon, and it really won't harm anything if it is spoofed, but that's super-ugly... – jab May 24 '13 at 19:47
  • For writing tests this behavior is ok, because you want to fake IPs. For a production system turn it off of course. – saintedlama May 24 '13 at 20:06
  • Yes, that's one option, but I was hoping to test the production code and not have to remember to modify it. :) – jab May 24 '13 at 20:44