Github user kxepal commented on a diff in the pull request:
https://github.com/apache/couchdb-couch/pull/80#discussion_r36049552
--- Diff: src/couch_httpd_csrf.erl ---
@@ -0,0 +1,177 @@
+% Licensed under the Apache License, Version 2.0 (the "License"); you may
not
+% use this file except in compliance with the License. You may obtain a
copy of
+% the License at
+%
+% http://www.apache.org/licenses/LICENSE-2.0
+%
+% Unless required by applicable law or agreed to in writing, software
+% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+% License for the specific language governing permissions and limitations
under
+% the License.
+
+%% This module provides optional CSRF protection to any client
+%%
+%% Clients should use the following pseudo code;
+%% if (hasCookie("CouchDB-CSRF")) {
+%% setRequestHeader("X-CouchDB-CSRF", cookieValue("CouchDB-CSRF"));
+%% } else {
+%% setRequestHeader("X-CouchDB-CSRF", "true")
+%% }
+%%
+%% If CouchDB sees the CouchDB-CSRF cookie then it checks its validity
+%% and whether the X-CouchDB-CSRF request header exists and matches.
+%% A 403 is returned if those checks fail.
+%% If CouchDB does not see the CouchDB-CSRF cookie but does see
+%% the X-CouchDB-CSRF header with value "true", a CouchDB-CSRF cookie
+%% is generated and returned.
+
+-module(couch_httpd_csrf).
+
+-export([validate/1, headers/2]).
+
+-include_lib("couch/include/couch_db.hrl").
+
+validate(#httpd{} = Req) ->
+ Cookie = csrf_from_req(Req),
+ Header = couch_httpd:header_value(Req, "X-CouchDB-CSRF"),
+ case {Cookie, Header} of
+ {undefined, undefined} ->
+ ok;
+ {undefined, "true"} ->
+ ok;
+ {undefined, _} ->
+ throw({forbidden, <<"CSRF header sent without cookie">>});
+ {Csrf, Csrf} ->
+ %% cookie and header match, but is it valid?
+ ok = validate(Csrf),
+
+ %% check expiration
+ {_, Timestamp, _} = decode_cookie(Csrf),
--- End diff --
You do `decode_cookie/1` in `validate/1` above where you handle `invalid`
result, but here you don't. Sure, it's not logically possible to get badmatch
here, but may be move check expiration to validate function to avoid decoding
same cookie twice?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---