Skip to content
3 changes: 2 additions & 1 deletion transmit-lib/src/cmr/transmit/config.clj
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,8 @@

(declare local-edl-verification)
(defconfig local-edl-verification
"Controls when cmr uses the EDL public key to locally verify JWT tokens."
"Controls when cmr uses the EDL public key to locally verify JWT tokens. When false, JWTs are
validated with EDL instead, which also catches tokens revoked in EDL."
{:type Boolean
:default true})

Expand Down
84 changes: 53 additions & 31 deletions transmit-lib/src/cmr/transmit/launchpad_user_cache.clj
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
(ns cmr.transmit.launchpad-user-cache
"Contains code for managing the launchpad user cache. We want to cache the launchpad token expiration date and username for
launchpad tokens to avoid needing to call out to EDL for authentication every time. Launchpad tokens have a lifetime currently of 60 minutes."
launchpad tokens to avoid needing to call out to EDL for authentication every time. Launchpad tokens have a lifetime currently of 60 minutes.
EDL JWTs validated with EDL, rather than locally, are cached here too for edl-token-cache-seconds."
(:require
[clj-time.core :as t]
[cmr.common.cache :as cache]
[cmr.common.cache.in-memory-cache :as mem-cache]
[cmr.common.config :refer [defconfig]]
[cmr.common.services.errors :as errors]
[cmr.common.time-keeper :as time-keeper]
[cmr.common.util :as common-util]
Expand All @@ -21,6 +23,12 @@
"The number of milliseconds launchpad token information will be cached."
(* 60 60 common-util/second-as-milliseconds))

(declare edl-token-cache-seconds)
(defconfig edl-token-cache-seconds
"How long a JWT validated with EDL is trusted before EDL is asked again. Search and ingest cache
the resulting permissions for up to 5 more minutes."
{:default 300 :type Long})

(defn create-launchpad-user-cache
"Creates a cache for which launchpad token users are stored in memory."
[]
Expand All @@ -30,61 +38,75 @@
"Error types that should not be cached - they are transient and should be retried immediately"
#{:too-many-requests :gateway-timeout})

(defn get-launchpad-user
"Get the launchpad user from cache or EDL.
Most errors are cached for 5 minutes then retried, preventing repeated requests with bad tokens.
Transient errors (429, 504) are not cached and passed through immediately."
[context token]
(let [get-launchpad-user-fn (fn []
(try
(let [resp (urs/get-launchpad-user context token)]
(assoc resp
:expiration-time (-> (or (:lp_token_expires_in resp)
(/ LAUNCHPAD_USER_CACHE_TIME 1000))
(t/seconds)
(t/from-now))
:valid true))
(catch Exception e
(let [error-type (:type (ex-data e))
error-msg (.getMessage e)]
;; Don't cache transient errors - rethrow immediately
(if (transient-error-types error-type)
(errors/throw-service-error error-type error-msg)
{:valid false
:error-message error-msg
:error-type error-type
:expiration-time (t/plus (time-keeper/now) (t/minutes (transmit-config/invalid-token-timeout)))})))))]
(defn- get-token-user
"Get the user for a token from cache, or by calling lookup-fn. lookup-fn returns the user info
with an :expiration-time. Most errors are cached for 5 minutes then retried, preventing repeated
requests with bad tokens. Transient errors (429, 504) are not cached and passed through immediately."
[context token lookup-fn]
(let [get-user-fn (fn []
(try
(assoc (lookup-fn) :valid true)
(catch Exception e
(let [error-type (:type (ex-data e))
error-msg (.getMessage e)]
;; Don't cache transient errors - rethrow immediately
(if (transient-error-types error-type)
(errors/throw-service-error error-type error-msg)
{:valid false
:error-message error-msg
:error-type error-type
:expiration-time (t/plus (time-keeper/now) (t/minutes (transmit-config/invalid-token-timeout)))})))))]
(if-let [cache (cache/context->cache context launchpad-user-cache-key)]
(let [cache-key (keyword (DigestUtils/sha256Hex token))
token-info (cache/get-value cache cache-key get-launchpad-user-fn)]
token-info (cache/get-value cache cache-key get-user-fn)]
(if (t/before? (:expiration-time token-info) (time-keeper/now))
;; Cache entry expired (after 5 min for errors, or token lifetime for valid tokens)
;; Evict and retry EDL
(do
(cache/evict cache cache-key)
(let [fresh-result (get-launchpad-user-fn)]
(let [fresh-result (get-user-fn)]
(if (:valid fresh-result)
(do
(cache/set-value cache cache-key fresh-result)
fresh-result)
(errors/throw-service-error
(or (:error-type fresh-result) :unauthorized)
(or (:error-message fresh-result)
(format "Invalid Launchpad token (partially redacted) [%s]"
(format "Invalid token (partially redacted) [%s]"
(common-util/scrub-token token)))))))
;; Cache entry still valid - return cached result or throw cached error
(if (:valid token-info)
token-info
(errors/throw-service-error
(or (:error-type token-info) :unauthorized)
(or (:error-message token-info)
(format "Invalid Launchpad token (partially redacted) [%s]"
(format "Invalid token (partially redacted) [%s]"
(common-util/scrub-token token)))))))
(let [result (get-launchpad-user-fn)]
(let [result (get-user-fn)]
(if (:valid result)
result
(errors/throw-service-error
(or (:error-type result) :unauthorized)
(or (:error-message result)
(format "Invalid Launchpad token (partially redacted) [%s]"
(format "Invalid token (partially redacted) [%s]"
(common-util/scrub-token token)))))))))

(defn get-launchpad-user
"Get the launchpad user from cache or EDL."
[context token]
(get-token-user context
token
#(let [resp (urs/get-launchpad-user context token)]
(assoc resp
:expiration-time (-> (or (:lp_token_expires_in resp)
(/ LAUNCHPAD_USER_CACHE_TIME 1000))
(t/seconds)
(t/from-now))))))

(defn get-edl-token-user
"Get the user for an EDL JWT from cache or by validating it with EDL."
[context token]
(get-token-user context
token
#(assoc (urs/get-token-user context token)
:expiration-time (t/from-now (t/seconds (edl-token-cache-seconds))))))
38 changes: 25 additions & 13 deletions transmit-lib/src/cmr/transmit/tokens.clj
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,12 @@
{:content-type :json
:body (json/encode body-obj)}))

(defn- loggable-params
[params]
(cond-> (select-keys params [:headers :form-params :content-type])
(get-in params [:headers "Authorization"]) (update-in [:headers "Authorization"] common-util/scrub-token)
(get-in params [:form-params :id]) (update-in [:form-params :id] common-util/scrub-token)))

(defn rest-post
"Makes a post request to echo-rest. Returns a tuple of status, the parsed body, and the body."
([context url-path body-obj]
Expand All @@ -149,7 +155,7 @@
params (if (some? (:form-params body-obj))
(merge (request-options conn) body-obj)
(merge (post-options conn body-obj) options))
_ (warn (format "Using legacy API call to POST %s with params: %s" url params))
_ (warn (format "Using legacy API call to POST %s with params: %s" url (loggable-params params)))
response (client/post url params)
{:keys [status body headers]} response
parsed (when (.startsWith ^String (get headers "Content-Type" "") "application/json")
Expand All @@ -159,17 +165,23 @@
(defn get-user-id
"Returns the user-id for the given token."
[context token]
(if (transmit-config/echo-system-token? token)
(cond
(transmit-config/echo-system-token? token)
(transmit-config/echo-system-username)
(if (and (common-util/is-jwt-token? token)
(transmit-config/local-edl-verification))

(common-util/is-jwt-token? token)
(if (transmit-config/local-edl-verification)
(verify-edl-token-locally token)
(if (common-util/is-launchpad-token? token)
(:uid (launchpad-user-cache/get-launchpad-user context token))
(let [[status parsed body] (rest-post context "/tokens/get_token_info"
{:headers {"Accept" mt/json
"Authorization" (transmit-config/echo-system-token)}
:form-params {:id token}})]
(info (format "get_token_info call on token [%s] (partially redacted) returned with status [%s]"
(common-util/scrub-token token) status))
(handle-get-user-id token status parsed body))))))
(:uid (launchpad-user-cache/get-edl-token-user context token)))

(common-util/is-launchpad-token? token)
(:uid (launchpad-user-cache/get-launchpad-user context token))

:else
(let [[status parsed body] (rest-post context "/tokens/get_token_info"
{:headers {"Accept" mt/json
"Authorization" (transmit-config/echo-system-token)}
:form-params {:id token}})]
(info (format "get_token_info call on token [%s] (partially redacted) returned with status [%s]"
(common-util/scrub-token token) status))
(handle-get-user-id token status parsed body))))
52 changes: 52 additions & 0 deletions transmit-lib/src/cmr/transmit/urs.clj
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
(ns cmr.transmit.urs
(:require
[clojure.string :as string]
[cmr.common.cache :as cache]
[cmr.common.cache.in-memory-cache :as mem-cache]
[cmr.common.log :refer [error]]
Expand Down Expand Up @@ -32,6 +33,10 @@
[conn]
(format "%s/api/nams/edl_user_uid" (conn/root-url conn)))

(defn- token-introspection-url
[conn]
(format "%s/oauth/introspect" (conn/root-url conn)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; URS cache functions

Expand Down Expand Up @@ -161,6 +166,53 @@
(common-util/scrub-token token)
status)))))))

(defn get-token-user
"Validates an EDL user or OAuth token with EDL token introspection. Returns {:uid uid}."
[context token]
(let [bare-token (string/replace (string/trim token) #"^Bearer\s+" "")
{:keys [status body]} (http-helper/request context :urs
{:url-fn token-introspection-url
:method :post
:raw? true
:http-options {:basic-auth [(config/urs-username)
(config/urs-password)]
:form-params {:token bare-token}}})
scrubbed (common-util/scrub-token token)
edl-error (when (map? body) (:error body))
;; EDL documents uid but returns the user as username and sub.
uid (when (map? body) (some body [:uid :username :sub]))]
(cond
(and (= 200 status) uid (not (false? (:active body))))
{:uid uid}

(= 401 status)
(errors/internal-error! "EDL rejected CMR's application credentials while validating a token.")

(= 408 status)
(errors/throw-service-error
:request-timeout
(format "Request timeout while validating token [%s]. Please try again later." scrubbed))

(= 429 status)
(errors/throw-service-error
:too-many-requests
(format "EDL rate limit exceeded while validating token [%s]. Please try again later." scrubbed))

(#{500 502 503 504} status)
(errors/throw-service-error
:dependency-failed
(format "EDL error while validating token [%s]. Please try again later. Status code [%d]."
scrubbed status))

:else
(do
(when-not (or (= "invalid_token" edl-error) (false? (:active body)))
(error (format "Unexpected EDL response validating token [%s]. Status code [%d]. Body [%s]"
scrubbed status (pr-str (common-util/trunc (str body) 500)))))
(errors/throw-service-error
:unauthorized
(format "Token %s does not exist" scrubbed))))))

(defn user-exists?
"Returns true if the given user exists in URS"
([context user]
Expand Down
37 changes: 37 additions & 0 deletions transmit-lib/test/cmr/transmit/test/edl_token_validation.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
(ns cmr.transmit.test.edl-token-validation
(:require
[clojure.test :refer [deftest is testing]]
[cmr.common.util :as common-util]
[cmr.transmit.config :as transmit-config]
[cmr.transmit.http-helper :as http-helper]
[cmr.transmit.launchpad-user-cache :as launchpad-user-cache]
[cmr.transmit.tokens :as tokens]
[cmr.transmit.urs :as urs]))

(def ^:private token "eyJ0eXAiOiJKV1QifQ.eyJ1aWQiOiJ1c2VyMSJ9.c2lnbmF0dXJlLXZhbHVl")
Comment thread
daniel-zamora marked this conversation as resolved.
Resolved

(defn- get-token-user
[response]
(let [sent (atom nil)]
(with-redefs [http-helper/request (fn [_ _ request] (reset! sent request) response)]
[(try
(urs/get-token-user {} (str "Bearer " token))
(catch clojure.lang.ExceptionInfo e (:type (ex-data e))))
@sent])))

(deftest get-token-user-test
(let [[result sent] (get-token-user {:status 200 :body {:username "user1" :sub "user1" :active true}})]
(is (= {:uid "user1"} result))
(is (= {:token token} (get-in sent [:http-options :form-params])))
(is (= [(transmit-config/urs-username) (transmit-config/urs-password)]
(get-in sent [:http-options :basic-auth]))))
(is (= :unauthorized (first (get-token-user {:status 400 :body {:error "invalid_token"}}))))
(is (= :unauthorized (first (get-token-user {:status 200 :body {:username "user1" :active false}}))))
(is (= :dependency-failed (first (get-token-user {:status 503 :body ""})))))

(deftest jwt-validated-with-edl-when-local-verification-off-test
(with-redefs [common-util/is-jwt-token? (constantly true)
transmit-config/local-edl-verification (constantly false)
launchpad-user-cache/get-edl-token-user (constantly {:uid "edl-user"})]
(testing "local verification off"
(is (= "edl-user" (tokens/get-user-id {} token))))))
18 changes: 18 additions & 0 deletions transmit-lib/test/cmr/transmit/test/tokens.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
(ns cmr.transmit.test.tokens
(:require
[clojure.string :as string]
[clojure.test :refer [deftest is]]
[cmr.transmit.tokens :as tokens]))

(deftest loggable-params-test
(let [system-token "system-token-0123456789-abcdefghij"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't we have a random text generator for using in tests instead of having a hard coded token?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it probably wouldn't hurt but this is more deterministic.

user-token "user-token-0123456789-abcdefghij"
logged (pr-str (#'tokens/loggable-params
{:connection-manager :pool
:socket-timeout 1000
:headers {"Authorization" system-token "Accept" "application/json"}
:form-params {:id user-token}}))]
(is (not (string/includes? logged system-token)))
(is (not (string/includes? logged user-token)))
(is (not (string/includes? logged ":connection-manager")))
(is (string/includes? logged "application/json"))))
Loading