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


##########
src/couch_replicator/src/couch_replicator_auth_ibm.erl:
##########
@@ -0,0 +1,708 @@
+% 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 allows a replication source or target to use an IAM api key for 
authentication.
+%
+% Features;
+%
+% Automatic refreshing of time-limited token before expiration
+% Deduplication - only one token will be acquired for each distinct IAM api key
+%
+% Implementation details
+%
+% As api keys are sensitive, the only copy of api keys is held in a private 
ETS table
+% owned by this module's gen_server. An opaque reference is returned to 
clients (this is
+% a message authentication code where the key is a non-persisted value 
generated by the
+% gen_server)
+
+-module(couch_replicator_auth_ibm).
+
+-behaviour(couch_replicator_auth).
+-behaviour(gen_server).
+-behaviour(config_listener).
+
+-export([
+    sup_initialize/0,
+    sup_cleanup/1,
+    initialize/1,
+    update_headers/2,
+    handle_response/3,
+    cleanup/1
+]).
+
+%% gen_server callbacks
+-export([
+    init/1,
+    handle_call/3,
+    handle_cast/2,
+    handle_info/2,
+    terminate/2
+]).
+
+% config_listener callbacks
+-export([
+    handle_config_change/5,
+    handle_config_terminate/3
+]).
+
+-include_lib("couch_replicator/include/couch_replicator_api_wrap.hrl").
+
+-define(MINUTE, 60).
+-define(PUBLIC, couch_replicator_auth_ibm_public).
+-define(PRIVATE, couch_replicator_auth_ibm_private).
+
+-record(worker_state, {
+    api_key_mac,
+    last_used
+}).
+
+-record(state, {
+    mac_key,
+    token_url
+}).
+
+-record(public_entry, {
+    api_key_mac,
+    token
+}).
+
+-record(private_entry, {
+    api_key_mac,
+    api_key_uuid,
+    api_key,
+    % Number of seconds (counted since January 1st, 1970) until the IAM access 
token will expire.
+    expires_at_secs,
+    acquire_mref,
+    used_since_acquisition,
+    waiters = []
+}).
+
+%% callbacks
+
+sup_initialize() ->
+    {ok, _} = gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
+
+sup_cleanup(_) ->
+    ok = gen_server:stop(?MODULE).
+
+initialize(#httpdb{} = HttpDb) ->
+    case extract_api_key(HttpDb) of
+        {ok, APIKey} ->
+            case gen_server:call(?MODULE, {register, APIKey}) of
+                {ok, APIKeyMAC} ->
+                    WorkerState = #worker_state{api_key_mac = APIKeyMAC, 
last_used = now_secs()},
+                    {ok, HttpDb, WorkerState};
+                {error, Reason} ->
+                    {error, Reason}
+            end;
+        {error, _} ->
+            ignore
+    end.
+
+update_headers(WorkerState, Headers) when is_list(Headers) ->
+    case get_token(WorkerState) of
+        {ok, Token} ->
+            {
+                [{~"Authorization", <<"Bearer ", Token/binary>>} | Headers],
+                update_used_since_acquisition(WorkerState)
+            };
+        {error, Reason} ->
+            couch_log:warning("Error when retrieving token: ~p", [Reason]),
+            {Headers, WorkerState}
+    end.
+
+handle_response(WorkerState, _StatusCode, _Headers) ->
+    {continue, WorkerState}.
+
+cleanup(_WorkerState) ->
+    ok.
+
+get_token(#worker_state{} = WorkerState) ->
+    #worker_state{api_key_mac = APIKeyMAC} = WorkerState,
+    case ets:lookup(?PUBLIC, APIKeyMAC) of
+        [#public_entry{token = Token}] when is_binary(Token) ->
+            {ok, Token};
+        [#public_entry{}] ->
+            gen_server:call(?MODULE, {get_token, APIKeyMAC}, 
request_timeout_ms());
+        [] ->
+            {error, no_token}
+    end.
+
+update_used_since_acquisition(#worker_state{} = WorkerState) ->
+    #worker_state{api_key_mac = APIKeyMAC, last_used = LastUsed} = WorkerState,
+    Now = now_secs(),
+    %% only send a message once per minute at most.
+    case Now - LastUsed > ?MINUTE of
+        true ->
+            ?MODULE ! {used_since_acquisition, APIKeyMAC},
+            WorkerState#worker_state{last_used = Now};
+        false ->
+            WorkerState
+    end.
+
+%% gen_server callbacks.
+
+init(_) ->
+    case token_url() of
+        {ok, TokenUrl} ->
+            ?PUBLIC = ets:new(?PUBLIC, [protected, {keypos, 
#public_entry.api_key_mac}, named_table]),
+            ?PRIVATE = ets:new(?PRIVATE, [
+                private, {keypos, #private_entry.api_key_mac}, named_table
+            ]),
+            ok = config:listen_for_changes(?MODULE, nil),
+            erlang:send_after(check_interval_ms(), self(), 
refresh_expire_check),
+            {ok, #state{
+                mac_key = crypto:strong_rand_bytes(32),
+                token_url = TokenUrl
+            }};
+        {error, Reason} ->
+            {error, Reason}
+    end.
+
+handle_call({register, APIKey}, _From, State) ->
+    case ets:match_object(?PRIVATE, #private_entry{api_key = APIKey, _ = '_'}) 
of
+        [#private_entry{} = Entry] ->
+            {reply, {ok, Entry#private_entry.api_key_mac}, State};
+        [] ->
+            AcquireMRef = acquire_token(APIKey, State),
+            APIKeyMAC = mac(State#state.mac_key, APIKey),
+            true = ets:insert_new(?PUBLIC, #public_entry{
+                api_key_mac = APIKeyMAC
+            }),
+            true = ets:insert_new(?PRIVATE, #private_entry{
+                api_key = APIKey,
+                api_key_mac = APIKeyMAC,
+                acquire_mref = AcquireMRef,
+                used_since_acquisition = false
+            }),
+            {reply, {ok, APIKeyMAC}, State}
+    end;
+handle_call({get_token, APIKeyMAC}, From, State) ->
+    case ets:lookup(?PUBLIC, APIKeyMAC) of
+        [] ->
+            {reply, {error, no_such_api_key}, State};
+        [#public_entry{token = Token}] when Token /= undefined ->
+            {reply, {ok, Token}, State};
+        [#public_entry{}] ->
+            [#private_entry{} = Entry] = ets:lookup(?PRIVATE, APIKeyMAC),
+            ets:insert(?PRIVATE, Entry#private_entry{waiters = [From | 
Entry#private_entry.waiters]}),
+            case Entry of
+                #private_entry{acquire_mref = AcquireMRef} when AcquireMRef /= 
undefined ->
+                    ok;
+                #private_entry{} ->
+                    self() ! {refresh_token, APIKeyMAC}
+            end,
+            {noreply, State}
+    end;
+handle_call(_Msg, _From, State) ->
+    {reply, {error, unexpected_msg}, State}.
+
+handle_cast(_Msg, State) ->
+    {noreply, State}.
+
+handle_info({used_since_acquisition, APIKeyMAC}, State) ->
+    ets:update_element(?PRIVATE, APIKeyMAC, 
{#private_entry.used_since_acquisition, true}),
+    {noreply, State};
+handle_info({refresh_token, APIKeyMAC}, State) ->
+    case ets:lookup(?PRIVATE, APIKeyMAC) of
+        [] ->
+            ok;
+        [#private_entry{acquire_mref = undefined} = Entry] ->
+            case Entry#private_entry.used_since_acquisition of
+                true ->
+                    couch_log:notice("~p: refreshing api key ~s", [
+                        ?MODULE, Entry#private_entry.api_key_uuid
+                    ]),
+                    AcquireMRef = acquire_token(Entry#private_entry.api_key, 
State),
+                    ets:insert(?PRIVATE, Entry#private_entry{acquire_mref = 
AcquireMRef});
+                false ->
+                    %% let it expire and free any waiters
+                    reply_and_reset(Entry, {error, token_expiring})
+            end;
+        [#private_entry{}] ->
+            ok
+    end,
+    {noreply, State};
+handle_info({expire_api_key_entry, APIKeyMAC}, State) ->
+    case ets:lookup(?PRIVATE, APIKeyMAC) of
+        [] ->
+            ok;
+        [#private_entry{} = Entry] ->
+            couch_log:warning("~p: api key entry ~s passed expiration time", [
+                ?MODULE, Entry#private_entry.api_key_uuid
+            ]),
+            ets:delete(?PUBLIC, APIKeyMAC),
+            ets:delete(?PRIVATE, APIKeyMAC),
+            if
+                Entry#private_entry.acquire_mref /= undefined ->
+                    demonitor(Entry#private_entry.acquire_mref, [flush]);
+                true ->
+                    ok
+            end,
+            reply_all(Entry#private_entry.waiters, {error, 
expired_api_key_entry})
+    end,
+    {noreply, State};
+handle_info(refresh_expire_check, #state{} = State) ->
+    NowSecs = now_secs(),
+    EarlyRefreshSecs = early_refresh_secs(),
+    Matches = ets:select(?PRIVATE, [
+        {
+            #private_entry{api_key_mac = '$1', expires_at_secs = '$2', _ = 
'_'},
+            [{'>=', '$2', NowSecs - EarlyRefreshSecs}],

Review Comment:
   I wonder if this is right? I think we'd want to find all entries for which 
`Now >= ExpiresAt - EarlyRefreshSec` that is equivalent to `ExpiresAt =< Now + 
EarlyRefreshSec`
   
   Then another thing to worry about is what happens if/when expires_at  is not 
an integer but `undefined`



##########
src/couch_replicator/src/couch_replicator_auth_ibm.erl:
##########
@@ -0,0 +1,708 @@
+% 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 allows a replication source or target to use an IAM api key for 
authentication.
+%
+% Features;
+%
+% Automatic refreshing of time-limited token before expiration
+% Deduplication - only one token will be acquired for each distinct IAM api key
+%
+% Implementation details
+%
+% As api keys are sensitive, the only copy of api keys is held in a private 
ETS table
+% owned by this module's gen_server. An opaque reference is returned to 
clients (this is
+% a message authentication code where the key is a non-persisted value 
generated by the
+% gen_server)
+
+-module(couch_replicator_auth_ibm).
+
+-behaviour(couch_replicator_auth).
+-behaviour(gen_server).
+-behaviour(config_listener).
+
+-export([
+    sup_initialize/0,
+    sup_cleanup/1,
+    initialize/1,
+    update_headers/2,
+    handle_response/3,
+    cleanup/1
+]).
+
+%% gen_server callbacks
+-export([
+    init/1,
+    handle_call/3,
+    handle_cast/2,
+    handle_info/2,
+    terminate/2
+]).
+
+% config_listener callbacks
+-export([
+    handle_config_change/5,
+    handle_config_terminate/3
+]).
+
+-include_lib("couch_replicator/include/couch_replicator_api_wrap.hrl").
+
+-define(MINUTE, 60).
+-define(PUBLIC, couch_replicator_auth_ibm_public).
+-define(PRIVATE, couch_replicator_auth_ibm_private).
+
+-record(worker_state, {
+    api_key_mac,
+    last_used
+}).
+
+-record(state, {
+    mac_key,
+    token_url
+}).
+
+-record(public_entry, {
+    api_key_mac,
+    token
+}).
+
+-record(private_entry, {
+    api_key_mac,
+    api_key_uuid,
+    api_key,
+    % Number of seconds (counted since January 1st, 1970) until the IAM access 
token will expire.
+    expires_at_secs,
+    acquire_mref,
+    used_since_acquisition,
+    waiters = []
+}).
+
+%% callbacks
+
+sup_initialize() ->
+    {ok, _} = gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
+
+sup_cleanup(_) ->
+    ok = gen_server:stop(?MODULE).
+
+initialize(#httpdb{} = HttpDb) ->
+    case extract_api_key(HttpDb) of
+        {ok, APIKey} ->
+            case gen_server:call(?MODULE, {register, APIKey}) of
+                {ok, APIKeyMAC} ->
+                    WorkerState = #worker_state{api_key_mac = APIKeyMAC, 
last_used = now_secs()},
+                    {ok, HttpDb, WorkerState};
+                {error, Reason} ->
+                    {error, Reason}
+            end;
+        {error, _} ->
+            ignore
+    end.
+
+update_headers(WorkerState, Headers) when is_list(Headers) ->
+    case get_token(WorkerState) of
+        {ok, Token} ->
+            {
+                [{~"Authorization", <<"Bearer ", Token/binary>>} | Headers],
+                update_used_since_acquisition(WorkerState)
+            };
+        {error, Reason} ->
+            couch_log:warning("Error when retrieving token: ~p", [Reason]),
+            {Headers, WorkerState}
+    end.
+
+handle_response(WorkerState, _StatusCode, _Headers) ->
+    {continue, WorkerState}.
+
+cleanup(_WorkerState) ->
+    ok.
+
+get_token(#worker_state{} = WorkerState) ->
+    #worker_state{api_key_mac = APIKeyMAC} = WorkerState,
+    case ets:lookup(?PUBLIC, APIKeyMAC) of
+        [#public_entry{token = Token}] when is_binary(Token) ->
+            {ok, Token};
+        [#public_entry{}] ->
+            gen_server:call(?MODULE, {get_token, APIKeyMAC}, 
request_timeout_ms());
+        [] ->
+            {error, no_token}
+    end.
+
+update_used_since_acquisition(#worker_state{} = WorkerState) ->
+    #worker_state{api_key_mac = APIKeyMAC, last_used = LastUsed} = WorkerState,
+    Now = now_secs(),
+    %% only send a message once per minute at most.
+    case Now - LastUsed > ?MINUTE of
+        true ->
+            ?MODULE ! {used_since_acquisition, APIKeyMAC},
+            WorkerState#worker_state{last_used = Now};
+        false ->
+            WorkerState
+    end.
+
+%% gen_server callbacks.
+
+init(_) ->
+    case token_url() of
+        {ok, TokenUrl} ->
+            ?PUBLIC = ets:new(?PUBLIC, [protected, {keypos, 
#public_entry.api_key_mac}, named_table]),
+            ?PRIVATE = ets:new(?PRIVATE, [
+                private, {keypos, #private_entry.api_key_mac}, named_table
+            ]),
+            ok = config:listen_for_changes(?MODULE, nil),
+            erlang:send_after(check_interval_ms(), self(), 
refresh_expire_check),
+            {ok, #state{
+                mac_key = crypto:strong_rand_bytes(32),
+                token_url = TokenUrl
+            }};
+        {error, Reason} ->
+            {error, Reason}
+    end.
+
+handle_call({register, APIKey}, _From, State) ->
+    case ets:match_object(?PRIVATE, #private_entry{api_key = APIKey, _ = '_'}) 
of
+        [#private_entry{} = Entry] ->
+            {reply, {ok, Entry#private_entry.api_key_mac}, State};
+        [] ->
+            AcquireMRef = acquire_token(APIKey, State),
+            APIKeyMAC = mac(State#state.mac_key, APIKey),
+            true = ets:insert_new(?PUBLIC, #public_entry{
+                api_key_mac = APIKeyMAC
+            }),
+            true = ets:insert_new(?PRIVATE, #private_entry{
+                api_key = APIKey,
+                api_key_mac = APIKeyMAC,
+                acquire_mref = AcquireMRef,
+                used_since_acquisition = false

Review Comment:
   I think this is still an issue. On first acquire failure the error sticks 
around and become persistent.  A job may crash then restart, re-registers and 
will find an entry already and repeat the cycle.
   
   Maybe the name is a bit mismatched. It seems like it should be something 
like "has anyone wanted a token since we handed one out already?" so if it's 
renamed as `wanted _since_token` it could match better with its use?
   
   On register we started as `true` (someone wanted a token), acquire succeeds 
(clear, we satisfied whoever wanted a token) set to false, then a message like 
`{wanted_since_token, MAC}` from update_headers and we check if should refresh. 
So then only thing that sets it to `false` is a successful acquire



-- 
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