apache/couchdb — pull request #172 by KlausTrainer (2014-03-10 23:45:35+00:00)
Title: Use cookie authentication during replication

In `couch_replicator_httpc:setup/1`, if the URL contains basic auth
credentials, the replicator now removes those credentials from the URL
and inserts them into a new ets table, whose identifier is stored in the
returned `httpdb` record in a new field named `credentials`.

Then, if during replication there's a HTTP status code 401, the
replicator does a POST-request to the remote DB's `/_session` endpoint,
in which the request body contains the user name and password from the
basic auth credentials stored in the ets table. If that request is
successful, the session cookie is inserted into the ets table together
with the current timestamp returned by `os:timestamp/0`. From that
point on, `couch_replicator_httpc:send_req/3` always retrieves the
cookie from the ets table and sets it as value in the "Cookie" request
header. When a new session cookie is set, the cookie value, together
with a new timestamp, will be updated in the ets table accordingly.
Now, after having started a new session, the request that generated the
response status code 401 is repeated.

In order to prevent the replicator from wrongly starting a new session
after getting a 401 status code and then repeating the request again
(and thereby causing an infinite loop), it is checked whether the
difference between the current timestamp returned by `os:timestamp/0`
and the timestamp stored together with the session cookie is greater
than one minute. A new session is started and the request is repeated
only if the difference is greater than one minute. Otherwise it is
proceeded as ever, i.e., the response with the 401 status code is
returned.