I asked a related question here. Basically, I have an API built with Flask, which I want to be able to POST to only from the same machine as is running the Flask app itself. All other POST requests should get a response of 401 Unauthorized.
I have become a little bit confused as to how to achieve that at this point. Elsewhere on SO (I can't recall where anymore) I read that comparing the REMOTE_ADDR header/field is the proper way to do this. Here is at least one example.
I wrote some code which I thought would do this in a view function:
if request.environ.get('REMOTE_ADDR', '127.0.0.1') != '127.0.0.1':
abort(401)
post_data = request.form
DPC().store(post_data)
return jsonify(post_data), 201
However, after implementing these changes, I was still able to POST to the API from an external machine. A test I wrote for this functionality belies what might be an underlying problem: def test_external_post_fails(self):
my_data = {
...
}
result = self.client.post('/daily_population_changes',
data=my_data,
environ_overrides={'REMOTE_ADDR': '127.0.0.2'})
assert result.status_code == 401
The test succeeds. But the question is one of accuracy, as opposed to precision: am I testing the right thing here? Does a remote request actually have a (non-null) value for REMOTE_ADDR in the Werkzeug environment that is not equal to '127.0.0.1'?
I haven't yet been able to actually inspect values as I would like to for these request objects, save to see (on a production server) that POST whitelisting is not succeeding. Perhaps someone already has insight into this, or else I will have access to more machines in a bit.
Thanks!