nickva commented on code in PR #5754:
URL: https://github.com/apache/couchdb/pull/5754#discussion_r2620704868


##########
src/couch/src/couch_secrets.erl:
##########
@@ -0,0 +1,180 @@
+% 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.
+
+-module(couch_secrets).
+
+-behaviour(gen_server).
+-behaviour(config_listener).
+
+-include_lib("couch/include/couch_db.hrl").
+
+%% public api
+-export([sign/1, sign/2, verify/2, verify/3, secret_is_set/0]).
+
+%% gen_server functions
+-export([
+    start_link/0,
+    init/1,
+    handle_call/3,
+    handle_cast/2,
+    handle_continue/2,
+    handle_info/2
+]).
+
+%% config_listener functions
+-export([
+    handle_config_change/5,
+    handle_config_terminate/3
+]).
+
+sign(Message) ->
+    sign(Message, <<>>).
+
+sign(Message, ExtraSecret) ->
+    [HashAlgorithm | _] = couch_util:get_config_hash_algorithms(),
+    case current_secret_from_ets() of
+        undefined ->
+            throw({internal_server_error, <<"cookie auth secret is not 
set">>});
+        CurrentSecret ->
+            FullSecret = <<CurrentSecret/binary, ExtraSecret/binary>>,
+            couch_util:hmac(HashAlgorithm, FullSecret, Message)
+    end.
+
+verify(Message, ExpectedMAC) ->
+    verify(Message, <<>>, ExpectedMAC).
+
+verify(Message, ExtraSecret, ExpectedMAC) ->
+    FullSecrets = [<<Secret/binary, ExtraSecret/binary>> || Secret <- 
all_secrets_from_ets()],
+    AllAlgorithms = couch_util:get_config_hash_algorithms(),
+    verify(Message, AllAlgorithms, FullSecrets, ExpectedMAC).
+
+verify(Message, AllAlgorithms, FullSecrets, ExpectedMAC) ->
+    VerifyFun = fun({Secret, Algorithm}) ->
+        ActualMAC = couch_util:hmac(Algorithm, Secret, Message),
+        case crypto:hash_info(Algorithm) of

Review Comment:
   I meant that technically we can filter out all the unsuitable algorithms 
before the nested `[{S, A} <- ...]` loop, since we can discard algorithms 
without looking at the secret by looking at `ExpectedMAC`'s length only.
   
   I guess practically it won't matter, we'll probably reject an algorithm at 
most once since we're unlikely to have more than two secrets at a time?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to