diff --git a/access-control-app/docs/api.md b/access-control-app/docs/api.md
index b3b8072e84..9e196b8312 100644
--- a/access-control-app/docs/api.md
+++ b/access-control-app/docs/api.md
@@ -17,6 +17,10 @@ See the [CMR Client Partner User Guide][client-guide] for a general guide to dev
* [POST - Check User Permissions](#get-permissions)
* [/s3-buckets](#s3-buckets)
* [GET - Check User Permissions to S3 Buckets](#get-s3-buckets)
+* [/token-denylist](#token-denylist)
+ * [GET - List deny list entries](#list-token-denylist)
+ * [PUT - Deny a token or user](#add-token-denylist)
+ * [DELETE - Remove a deny list entry](#remove-token-denylist)
* [/health](#health)
* [GET - Get the health of the access control application.](#application-health)
@@ -789,6 +793,50 @@ Content-Type: application/json
["s3://aws.example-2.com","s3://aws.example-3.com"]
```
+
+## Token Deny List
+
+Search, ingest and access control reject requests whose token, or the user it belongs to, is on the deny list, with a 401. Each application reloads the list every 30 seconds (`CMR_TOKEN_DENYLIST_REFRESH_SECONDS`). User ids match case-insensitively, and a listed user's subscriptions stop sending notifications. While the list has user entries, each request's token is resolved to its user first; if that fails, the request gets that error (401 for an invalid or expired token, 528 if EDL can't be reached). These endpoints require system level `INGEST_MANAGEMENT_ACL` permission (read to list, update to change), and changes also require a token that passes the write token check.
+
+A token entry is a SHA-256 hex digest. For an EDL JWT it covers the signed header and payload, the part before the second `.`; for any other token it covers the whole token, without a `Bearer ` prefix or surrounding whitespace. Prefer the `token_hash` that search and ingest log; otherwise compute it from the bare token with:
+
+ printf '%s' "${TOKEN%.*}" | sha256sum # EDL JWT
+ printf '%s' "$TOKEN" | sha256sum # other tokens
+
+### List Deny List Entries
+
+```
+curl -i -H "Authorization: Bearer XXXX" %CMR-ENDPOINT%/token-denylist
+
+HTTP/1.1 200 OK
+Content-Type: application/json;charset=utf-8
+
+{"tokens":[{"reason":"leaked","added_by":"admin1","added_at":"2026-11-12T18:04:11.123Z","hash":"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"}],"users":[{"reason":null,"added_by":"admin1","added_at":"2026-11-12T18:05:40.012Z","user_id":"user1"}]}
+```
+
+### Deny a Token or User
+
+`PUT /token-denylist/tokens/` or `PUT /token-denylist/users/`. The body is optional; if sent, it must be JSON with `Content-Type: application/json` and only takes `reason`, a string of at most 500 characters.
+
+```
+curl -i -XPUT -H "Authorization: Bearer XXXX" -H "Content-Type: application/json" %CMR-ENDPOINT%/token-denylist/users/user1 -d '{"reason": "abuse"}'
+
+HTTP/1.1 200 OK
+Content-Type: application/json;charset=utf-8
+
+{"reason":"abuse","added_by":"admin1","added_at":"2026-11-12T18:05:40.012Z"}
+```
+
+### Remove a Deny List Entry
+
+Returns 204, or 404 if there is no such entry.
+
+```
+curl -i -XDELETE -H "Authorization: Bearer XXXX" %CMR-ENDPOINT%/token-denylist/users/user1
+
+HTTP/1.1 204 No Content
+```
+
## Health
### Application Health
diff --git a/access-control-app/src/cmr/access_control/api/routes.clj b/access-control-app/src/cmr/access_control/api/routes.clj
index bde9877998..7348a865d3 100644
--- a/access-control-app/src/cmr/access_control/api/routes.clj
+++ b/access-control-app/src/cmr/access_control/api/routes.clj
@@ -17,6 +17,7 @@
[cmr.common-app.api.health :as common-health]
[cmr.common-app.api.launchpad-token-validation :as lt-validation]
[cmr.common-app.api.routes :as common-routes]
+ [cmr.common-app.api.token-denylist :as token-denylist]
[cmr.common-app.services.search.parameter-validation :as cpv]
[cmr.common.cache :as cache]
[cmr.common.log :refer (info error)]
@@ -302,6 +303,8 @@
;; add routes for accessing caches
common-routes/cache-api-routes
+ token-denylist/token-denylist-api-routes
+
;; Reindex all groups
(POST "/reindex-groups"
{ctx :request-context params :params}
diff --git a/access-control-app/src/cmr/access_control/routes.clj b/access-control-app/src/cmr/access_control/routes.clj
index ebbbd626b5..1d6e56f9aa 100644
--- a/access-control-app/src/cmr/access_control/routes.clj
+++ b/access-control-app/src/cmr/access_control/routes.clj
@@ -10,6 +10,7 @@
[cmr.acl.core :as acl]
[cmr.common-app.api.request-logger :as req-log]
[cmr.common-app.api.routes :as common-routes]
+ [cmr.common-app.api.token-denylist :as token-denylist]
[cmr.common-app.site.pages :as common-pages]
[cmr.common.api.context :as context]
[cmr.common.api.errors :as api-errors]
@@ -26,6 +27,7 @@
(defn handlers [system]
(-> (build-routes system)
+ token-denylist/deny-listed-token-handler
acl/add-authentication-handler
common-routes/add-request-id-response-handler
req-log/log-ring-request ;; Must be after request id
diff --git a/access-control-app/src/cmr/access_control/services/acl_service.clj b/access-control-app/src/cmr/access_control/services/acl_service.clj
index 82137c231a..cc5347ce78 100644
--- a/access-control-app/src/cmr/access_control/services/acl_service.clj
+++ b/access-control-app/src/cmr/access_control/services/acl_service.clj
@@ -14,6 +14,7 @@
[cmr.access-control.services.parameter-validation :as pv]
[cmr.acl.core :as acl]
[cmr.common-app.api.enabled :as common-enabled]
+ [cmr.common-app.api.token-denylist :as token-denylist]
[cmr.common-app.services.provider-cache :as provider-cache]
[cmr.common.concepts :as concepts]
[cmr.common.log :refer [warn info]]
@@ -415,7 +416,9 @@
;; If token is nil or empty, treat as guest
(if (or (nil? user-token)(re-matches #"^[\s\t]*$" user-token))
(auth-util/get-sids context :guest)
- (auth-util/get-sids context (tokens/get-user-id context user-token)))))
+ (do
+ (token-denylist/verify-token-allowed context user-token)
+ (auth-util/get-sids context (tokens/get-user-id context user-token))))))
(defn- fix-single-string-with-multiple-values
"Check if string has embedded array, if not then return result conj'd with results,
diff --git a/access-control-app/src/cmr/access_control/system.clj b/access-control-app/src/cmr/access_control/system.clj
index 7aad0e9574..2fe030751b 100644
--- a/access-control-app/src/cmr/access_control/system.clj
+++ b/access-control-app/src/cmr/access_control/system.clj
@@ -12,6 +12,7 @@
[cmr.acl.core :as acl]
[cmr.common-app.api.enabled :as common-enabled]
[cmr.common-app.api.health :as common-health]
+ [cmr.common-app.api.request-context-user-augmenter :as context-augmenter]
[cmr.common-app.services.provider-cache :as provider-cache]
[cmr.common.api.web-server :as web-server]
[cmr.common.config :as cfg :refer [defconfig]]
@@ -24,6 +25,7 @@
[cmr.message-queue.queue.queue-broker :as queue-broker]
[cmr.transmit.config :as transmit-config]
[cmr.transmit.launchpad-user-cache :as launchpad-user-cache]
+ [cmr.transmit.token-denylist :as token-denylist]
[cmr.transmit.urs :as urs]))
(declare access-control-nrepl-port)
@@ -98,7 +100,9 @@
common-enabled/write-enabled-cache-key (common-enabled/create-write-enabled-cache)
common-health/health-cache-key (common-health/create-health-cache)
launchpad-user-cache/launchpad-user-cache-key (launchpad-user-cache/create-launchpad-user-cache)
- urs/urs-cache-key (urs/create-urs-cache)})
+ urs/urs-cache-key (urs/create-urs-cache)
+ token-denylist/snapshot-cache-key (token-denylist/create-snapshot-cache)
+ context-augmenter/token-user-id-cache-name (context-augmenter/create-token-user-id-cache)})
(def hours->ms "Convert hours to ms" (partial * 1000 3600))
diff --git a/common-app-lib/src/cmr/common_app/api/token_denylist.clj b/common-app-lib/src/cmr/common_app/api/token_denylist.clj
new file mode 100644
index 0000000000..1912984429
--- /dev/null
+++ b/common-app-lib/src/cmr/common_app/api/token_denylist.clj
@@ -0,0 +1,151 @@
+(ns cmr.common-app.api.token-denylist
+ "Rejects requests whose token, or the user it belongs to, is on the token deny list, and
+ defines the routes for managing the list."
+ (:require
+ [cheshire.core :as json]
+ [clojure.string :as string]
+ [cmr.acl.core :as acl]
+ [cmr.common-app.api.launchpad-token-validation :as lt-validation]
+ [cmr.common-app.api.request-context-user-augmenter :as context-augmenter]
+ [cmr.common.cache :as cache]
+ [cmr.common.log :refer [info]]
+ [cmr.common.mime-types :as mt]
+ [cmr.common.services.errors :as errors]
+ [cmr.common.time-keeper :as tk]
+ [cmr.common.util :as util]
+ [cmr.transmit.config :as transmit-config]
+ [cmr.transmit.token-denylist :as denylist]
+ [cmr.transmit.tokens :as tokens]
+ [compojure.core :refer [context DELETE GET PUT]])
+ (:import
+ (org.apache.commons.codec.digest DigestUtils)))
+
+(defn- token->user-id
+ [ctx token]
+ ;; Legacy tokens can't authenticate now that the ECHO REST endpoint is retired; hash only.
+ (when-not (util/is-legacy-token? token)
+ (or (when (= token (:token ctx))
+ (util/get-real-or-lazy ctx :user-id))
+ (if-let [user-id-cache (cache/context->cache ctx context-augmenter/token-user-id-cache-name)]
+ ;; Hashed key, since the cache API can list keys.
+ (cache/get-value user-id-cache (DigestUtils/sha256Hex ^String token) #(tokens/get-user-id ctx token))
+ (tokens/get-user-id ctx token)))))
+
+(defn verify-token-allowed
+ "Throws unauthorized when the token, by default the context's, or its user is on the deny list."
+ ([ctx]
+ (verify-token-allowed ctx (:token ctx)))
+ ([ctx token]
+ (when (and token
+ (not (transmit-config/echo-system-token? token))
+ (denylist/denied? ctx token #(token->user-id ctx token)))
+ (errors/throw-service-error
+ :unauthorized
+ (format "Token [%s] has been revoked. Note the token value has been partially redacted."
+ (util/scrub-token token))))))
+
+(defn deny-listed-token-handler
+ "Ring handler that rejects deny-listed tokens. It must run after the token is added to the
+ request context."
+ [handler]
+ (fn [request]
+ (verify-token-allowed (:request-context request))
+ (handler request)))
+
+(def ^:private path->entry-type
+ {"tokens" :token
+ "users" :user})
+
+(defn- validate-id
+ [entry-type id]
+ (let [id (string/lower-case id)]
+ (when-not (if (= :token entry-type)
+ (re-matches #"[0-9a-f]{64}" id)
+ (re-matches #"[\x21-\x7E]+" id))
+ (errors/throw-service-error
+ :bad-request
+ (if (= :token entry-type)
+ "Token entries are identified by the token's SHA-256 hash in hex."
+ "User id must be printable ASCII with no whitespace.")))
+ id))
+
+(def ^:private max-reason-length 500)
+
+(defn- parse-reason
+ [body]
+ (when-not (string/blank? body)
+ (let [parsed (try
+ (json/parse-string body true)
+ (catch Exception _
+ (errors/throw-service-error :bad-request "Request body must be JSON.")))
+ reason (when (map? parsed) (:reason parsed))]
+ (when-not (map? parsed)
+ (errors/throw-service-error :bad-request "Request body must be a JSON object."))
+ (when-not (or (nil? reason) (and (string? reason) (<= (count reason) max-reason-length)))
+ (errors/throw-service-error
+ :bad-request
+ (format "reason must be a string of at most %d characters." max-reason-length)))
+ reason)))
+
+(defn- json-response
+ [status body]
+ {:status status
+ :headers {"Content-Type" (mt/with-utf-8 mt/json)}
+ :body (json/generate-string body)})
+
+(defn- entries-response
+ [entries]
+ {:tokens (for [[token-hash metadata] (:token entries)]
+ (assoc metadata :hash token-hash))
+ :users (for [[user-id metadata] (:user entries)]
+ (assoc metadata :user_id user-id))})
+
+(defn- requesting-user
+ [ctx]
+ (some->> (:token ctx) (tokens/get-user-id ctx)))
+
+(defn- add-entry
+ [ctx entry-type id body]
+ (let [id (validate-id entry-type id)
+ metadata {:reason (parse-reason body)
+ :added_by (requesting-user ctx)
+ :added_at (str (tk/now))}]
+ (denylist/add-entry! entry-type id metadata)
+ (denylist/reload-snapshot ctx)
+ (info (format "User [%s] added %s [%s] to the token deny list. Reason: %s"
+ (:added_by metadata) (name entry-type) id (pr-str (:reason metadata))))
+ (json-response 200 metadata)))
+
+(defn- remove-entry
+ [ctx entry-type id]
+ (let [id (validate-id entry-type id)
+ user (requesting-user ctx)]
+ (if (denylist/remove-entry! entry-type id)
+ (do
+ (denylist/reload-snapshot ctx)
+ (info (format "User [%s] removed %s [%s] from the token deny list." user (name entry-type) id))
+ {:status 204})
+ (json-response 404 {:errors [(format "No %s deny list entry for [%s]." (name entry-type) id)]}))))
+
+(defn- verify-write
+ [ctx]
+ (lt-validation/validate-write-token ctx)
+ (acl/verify-ingest-management-permission ctx :update))
+
+(def token-denylist-api-routes
+ "Routes for listing, adding and removing deny list entries. Callers need system ingest
+ management permission."
+ (context "/token-denylist" []
+ (GET "/" {ctx :request-context}
+ (acl/verify-ingest-management-permission ctx :read)
+ (json-response 200 (entries-response (denylist/get-entries))))
+ (context ["/:entry-path/:id" :entry-path #"tokens|users"] [entry-path id]
+ (PUT "/" {ctx :request-context body :body headers :headers}
+ (verify-write ctx)
+ (when-let [content-type (get headers "content-type")]
+ (when-not (string/starts-with? (string/lower-case content-type) mt/json)
+ (errors/throw-service-error :bad-request "Content-Type must be application/json.")))
+ (add-entry ctx (path->entry-type entry-path) id (some-> body slurp)))
+ (DELETE "/" {ctx :request-context}
+ (verify-write ctx)
+ (remove-entry ctx (path->entry-type entry-path) id)))))
diff --git a/common-app-lib/test/cmr/common_app/test/api/token_denylist.clj b/common-app-lib/test/cmr/common_app/test/api/token_denylist.clj
new file mode 100644
index 0000000000..94f5f4e0b0
--- /dev/null
+++ b/common-app-lib/test/cmr/common_app/test/api/token_denylist.clj
@@ -0,0 +1,56 @@
+(ns cmr.common-app.test.api.token-denylist
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [cmr.acl.core :as acl]
+ [cmr.common-app.api.launchpad-token-validation :as lt-validation]
+ [cmr.common-app.api.token-denylist :as token-denylist]
+ [cmr.transmit.config :as transmit-config]
+ [cmr.transmit.token-denylist :as denylist]
+ [cmr.transmit.tokens :as tokens]))
+
+(def ^:private user-token (apply str (repeat 120 "t")))
+
+(defn- error-type
+ [f]
+ (try
+ (f)
+ nil
+ (catch clojure.lang.ExceptionInfo e
+ (:type (ex-data e)))))
+
+(deftest verify-token-allowed-test
+ (with-redefs [denylist/denied? (fn [_ _ user-id-fn] (= "user1" (user-id-fn)))
+ tokens/get-user-id (constantly "user1")]
+ (is (= :unauthorized (error-type #(token-denylist/verify-token-allowed {:token user-token}))))
+ ;; Legacy tokens resolve through a call that logs the token, so they are never looked up.
+ (is (nil? (token-denylist/verify-token-allowed {:token "short-legacy-token"}))))
+ (with-redefs [denylist/denied? (constantly true)]
+ (is (nil? (token-denylist/verify-token-allowed {})))
+ (is (nil? (token-denylist/verify-token-allowed {:token (transmit-config/echo-system-token)})))))
+
+(deftest add-entry-route-test
+ (let [added (atom nil)]
+ (with-redefs [acl/verify-ingest-management-permission (constantly nil)
+ lt-validation/validate-write-token (constantly nil)
+ denylist/add-entry! (fn [& args] (reset! added args))
+ denylist/reload-snapshot (constantly nil)
+ tokens/get-user-id (constantly "admin1")]
+ (is (= 200 (:status (token-denylist/token-denylist-api-routes
+ {:request-method :put
+ :uri (str "/token-denylist/tokens/" (apply str (repeat 64 "A")))
+ :request-context {:token "admin-token"}}))))
+ (is (= [:token (apply str (repeat 64 "a"))] (take 2 @added)))
+ (is (= :bad-request (error-type #(token-denylist/token-denylist-api-routes
+ {:request-method :put
+ :uri "/token-denylist/tokens/not-a-hash"
+ :request-context {:token "admin-token"}}))))
+ (testing "user ids are stored lowercased"
+ (token-denylist/token-denylist-api-routes
+ {:request-method :put :uri "/token-denylist/users/JDoe" :request-context {:token "admin-token"}})
+ (is (= [:user "jdoe"] (take 2 @added))))
+ (testing "reason must be a string"
+ (is (= :bad-request (error-type #(token-denylist/token-denylist-api-routes
+ {:request-method :put
+ :uri "/token-denylist/users/jdoe"
+ :request-context {:token "admin-token"}
+ :body (java.io.ByteArrayInputStream. (.getBytes "{\"reason\": [1]}"))}))))))))
diff --git a/ingest-app/src/cmr/ingest/api/core.clj b/ingest-app/src/cmr/ingest/api/core.clj
index 34d0780b1c..a01f5172f9 100644
--- a/ingest-app/src/cmr/ingest/api/core.clj
+++ b/ingest-app/src/cmr/ingest/api/core.clj
@@ -7,6 +7,7 @@
[cmr.acl.core :as acl]
[cmr.common-app.api.enabled :as common-enabled]
[cmr.common-app.api.launchpad-token-validation :as lt-validation]
+ [cmr.common-app.api.request-context-user-augmenter :as context-augmenter]
[cmr.common.cache :as cache]
[cmr.common.cache.in-memory-cache :as mem-cache]
[cmr.common.log :refer [info]]
@@ -16,6 +17,7 @@
[cmr.ingest.services.messages :as msg]
[cmr.ingest.services.providers-cache :as pc]
[cmr.transmit.config :as transmit-config]
+ [cmr.transmit.token-denylist :as token-denylist]
[cmr.transmit.tokens :as tokens]
[cmr.common.util :as util])
(:import
@@ -288,15 +290,38 @@
[concept]
(pr-str (dissoc concept :metadata)))
+(defn- known-user-id
+ "Returns the user id for the request's token if it is already known, without calling out to
+ resolve it."
+ [request-context]
+ (when-let [token (:token request-context)]
+ (or (:user-id request-context)
+ (let [user-id-delay (get request-context (util/key->delay-name :user-id))]
+ (when (and user-id-delay (realized? user-id-delay))
+ (try @user-id-delay (catch Exception _ nil))))
+ (some-> (cache/context->cache request-context user-id-cache-key)
+ (cache/get-value token))
+ (some-> (cache/context->cache request-context context-augmenter/token-user-id-cache-name)
+ (cache/get-value token))
+ (when (util/is-jwt-token? token)
+ (:uid (tokens/get-jwt-claims token))))))
+
+(defn token-hash
+ "Returns the deny list hash of the request's token, for logging."
+ [request-context]
+ (token-denylist/token-hash-for-log (:token request-context)))
+
(defn log-concept-with-metadata-size
"Log the concept with metadata-size-bytes added, and metadata removed."
[concept request-context]
(let [metadata-size-bytes (-> (:metadata concept) (.getBytes "UTF-8") alength)
concept (assoc concept :metadata-size-bytes metadata-size-bytes)]
- (info (format "Successfully ingested %s from client %s, token_type %s"
+ (info (format "Successfully ingested %s from client %s, token_type %s, user %s, token_hash %s"
(concept->loggable-string concept)
(:client-id request-context)
- (lt-validation/get-token-type (:token request-context))))))
+ (lt-validation/get-token-type (:token request-context))
+ (known-user-id request-context)
+ (token-hash request-context)))))
(defn set-default-error-format
"Ring middleware to add a default format to the exception-info created during exceptions. This
@@ -325,8 +350,9 @@
(common-enabled/validate-write-enabled request-context "ingest")
(verify-provider-exists request-context provider-id)
(acl/verify-ingest-management-permission request-context :update :provider-object provider-id)
- (info (format "Deleting %s %s from client %s"
- (name concept-type) (pr-str concept-attribs) (:client-id request-context)))
+ (info (format "Deleting %s %s from client %s, token_hash %s"
+ (name concept-type) (pr-str concept-attribs) (:client-id request-context)
+ (token-hash request-context)))
(generate-ingest-response headers
(format-and-contextualize-warnings-existing-errors
(ingest/delete-concept
diff --git a/ingest-app/src/cmr/ingest/api/granules.clj b/ingest-app/src/cmr/ingest/api/granules.clj
index 8c9fd5eb8e..f0f8997723 100644
--- a/ingest-app/src/cmr/ingest/api/granules.clj
+++ b/ingest-app/src/cmr/ingest/api/granules.clj
@@ -93,6 +93,7 @@
(api-core/verify-provider-exists request-context provider-id)
(acl/verify-ingest-management-permission request-context :update :provider-object provider-id)
(common-enabled/validate-write-enabled request-context "ingest")
- (info (format "Deleting granule %s from client %s"
- (pr-str concept-attribs) (:client-id request-context)))
+ (info (format "Deleting granule %s from client %s, token_hash %s"
+ (pr-str concept-attribs) (:client-id request-context)
+ (api-core/token-hash request-context)))
(api-core/generate-ingest-response headers (ingest/delete-granule request-context concept-attribs))))
diff --git a/ingest-app/src/cmr/ingest/api/subscriptions.clj b/ingest-app/src/cmr/ingest/api/subscriptions.clj
index f80ffea7c4..5079959099 100644
--- a/ingest-app/src/cmr/ingest/api/subscriptions.clj
+++ b/ingest-app/src/cmr/ingest/api/subscriptions.clj
@@ -440,8 +440,9 @@
(api-core/set-revision-id headers)
(api-core/set-user-id request-context headers))]
(check-ingest-permission request-context provider-id subscriber-id)
- (info (format "Deleting subscription %s from client %s"
- (pr-str concept-attribs) (:client-id request-context)))
+ (info (format "Deleting subscription %s from client %s, token_hash %s"
+ (pr-str concept-attribs) (:client-id request-context)
+ (api-core/token-hash request-context)))
(api-core/generate-ingest-response headers
(api-core/format-and-contextualize-warnings-existing-errors
(ingest/delete-subscription
diff --git a/ingest-app/src/cmr/ingest/routes.clj b/ingest-app/src/cmr/ingest/routes.clj
index 93cb05e487..2f23a47c2d 100644
--- a/ingest-app/src/cmr/ingest/routes.clj
+++ b/ingest-app/src/cmr/ingest/routes.clj
@@ -11,6 +11,7 @@
[cmr.common-app.api.request-context-user-augmenter :as context-augmenter]
[cmr.common-app.api.request-logger :as req-log]
[cmr.common-app.api.routes :as common-routes]
+ [cmr.common-app.api.token-denylist :as token-denylist]
[cmr.common-app.site.pages :as common-pages]
[cmr.common.api.context :as context]
[cmr.ingest.site.routes :as site-routes]
@@ -36,6 +37,7 @@
(defn handlers [system]
(-> (build-routes system)
+ token-denylist/deny-listed-token-handler
;; add-authentication-handler adds the token and client id for user to
;; the context add-user-id-and-sids-handler lazy adds the user id and
;; sids for that token Need to maintain this order (works backwards).
diff --git a/ingest-app/src/cmr/ingest/services/nrt_subscription/subscriptions.clj b/ingest-app/src/cmr/ingest/services/nrt_subscription/subscriptions.clj
index 6f569de6ab..714423c269 100644
--- a/ingest-app/src/cmr/ingest/services/nrt_subscription/subscriptions.clj
+++ b/ingest-app/src/cmr/ingest/services/nrt_subscription/subscriptions.clj
@@ -8,7 +8,8 @@
[cmr.ingest.config :as ingest-config]
[cmr.transmit.metadata-db2 :as mdb2]
[cmr.ingest.services.nrt-subscription.subscription-cache :as subscription-cache]
- [cmr.transmit.config :as t-config])
+ [cmr.transmit.config :as t-config]
+ [cmr.transmit.token-denylist :as token-denylist])
(:import
(org.apache.commons.validator.routines UrlValidator)))
@@ -372,7 +373,9 @@
message (create-notification-message-body context concept)
message-attributes-map (create-message-attributes-map endpoint-set gran-concept-mode coll-concept-id)
subject (create-message-subject gran-concept-mode)]
- (when (and message-attributes-map subject)
+ (when (and message-attributes-map
+ subject
+ (not (token-denylist/user-denied? context (second endpoint-set))))
(let [result (topic-protocol/publish topic message message-attributes-map subject)
duration (- (System/currentTimeMillis) start)]
(debug (format "Subscription publish for endpoint %s took %d ms." (first endpoint-set) duration))
diff --git a/ingest-app/src/cmr/ingest/services/subscriptions_helper.clj b/ingest-app/src/cmr/ingest/services/subscriptions_helper.clj
index d8e45cc5ea..b8cdda48c6 100644
--- a/ingest-app/src/cmr/ingest/services/subscriptions_helper.clj
+++ b/ingest-app/src/cmr/ingest/services/subscriptions_helper.clj
@@ -14,6 +14,7 @@
[cmr.transmit.config :as config]
[cmr.transmit.metadata-db :as mdb]
[cmr.transmit.search :as search]
+ [cmr.transmit.token-denylist :as token-denylist]
[cmr.transmit.urs :as urs]
[markdown.core :as markdown]
[postal.core :as postal-core]))
@@ -117,7 +118,8 @@
"Takes a list of concept references and a subscriber id and removes any concept that the user does
not have read access to."
[context concept-refs subscriber-id]
- (when (seq concept-refs)
+ (when (and (seq concept-refs)
+ (not (token-denylist/user-denied? context subscriber-id)))
(let [permissions (json/parse-string
(access-control/get-permissions context {:user_id subscriber-id
:concept_id (map :concept-id concept-refs)}))]
diff --git a/ingest-app/src/cmr/ingest/system.clj b/ingest-app/src/cmr/ingest/system.clj
index 7d570b3f25..fa8118dd57 100644
--- a/ingest-app/src/cmr/ingest/system.clj
+++ b/ingest-app/src/cmr/ingest/system.clj
@@ -33,6 +33,7 @@
[cmr.metadata-db.services.util :as mdb-util]
[cmr.transmit.config :as transmit-config]
[cmr.transmit.launchpad-user-cache :as launchpad-user-cache]
+ [cmr.transmit.token-denylist :as token-denylist]
[cmr.transmit.urs :as urs]))
(def ^:private component-order
@@ -110,6 +111,7 @@
humanizer-alias-cache/humanizer-alias-cache-key (humanizer-alias-cache/create-cache-client)
launchpad-user-cache/launchpad-user-cache-key (launchpad-user-cache/create-launchpad-user-cache)
urs/urs-cache-key (urs/create-urs-cache)
+ token-denylist/snapshot-cache-key (token-denylist/create-snapshot-cache)
generic-validation/schema-validation-cache-key (generic-validation/create-schema-validation-cache)
subscription-cache/subscription-cache-key (subscription-cache/create-cache-client)})
diff --git a/ingest-app/test/cmr/ingest/test/api/core.clj b/ingest-app/test/cmr/ingest/test/api/core.clj
new file mode 100644
index 0000000000..7e62d504af
--- /dev/null
+++ b/ingest-app/test/cmr/ingest/test/api/core.clj
@@ -0,0 +1,14 @@
+(ns cmr.ingest.test.api.core
+ (:require
+ [clojure.test :refer [deftest is]]
+ [cmr.common.util :as util]
+ [cmr.ingest.api.core :as api-core]))
+
+(deftest known-user-id-does-not-resolve-test
+ (let [resolved? (atom false)
+ context (util/lazy-assoc {:token (apply str (repeat 120 "t"))}
+ :user-id (do (reset! resolved? true) "user1"))]
+ (is (nil? (#'api-core/known-user-id context)))
+ (is (false? @resolved?))
+ (util/lazy-get context :user-id)
+ (is (= "user1" (#'api-core/known-user-id context)))))
diff --git a/search-app/src/cmr/search/api/concepts_search.clj b/search-app/src/cmr/search/api/concepts_search.clj
index ba3c677de3..2913363475 100644
--- a/search-app/src/cmr/search/api/concepts_search.clj
+++ b/search-app/src/cmr/search/api/concepts_search.clj
@@ -20,6 +20,7 @@
[cmr.search.services.query-service :as query-svc]
[cmr.search.services.result-format-helper :as rfh]
[cmr.search.validators.all-granule-validation :as all-gran-validation]
+ [cmr.transmit.token-denylist :as token-denylist]
[compojure.core :refer :all]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@@ -288,8 +289,9 @@
"Retrieves a timeline of granules within each collection found."
[ctx path-w-extension params headers query-string]
(let [params (core-api/process-params :granule params path-w-extension headers mt/json)
- _ (info (format "Getting granule timeline from client %s, token_type %s with params %s."
- (:client-id ctx) (get-token-type (:token ctx)) (pr-str params)))
+ _ (info (format "Getting granule timeline from client %s, token_type %s, token_hash %s with params %s."
+ (:client-id ctx) (get-token-type (:token ctx))
+ (token-denylist/token-hash-for-log (:token ctx)) (pr-str params)))
search-params (lp/process-legacy-psa params)]
(core-api/search-response ctx (query-svc/get-granule-timeline ctx search-params))))
diff --git a/search-app/src/cmr/search/api/core.clj b/search-app/src/cmr/search/api/core.clj
index fb8edcfa69..f38815d21a 100644
--- a/search-app/src/cmr/search/api/core.clj
+++ b/search-app/src/cmr/search/api/core.clj
@@ -7,6 +7,7 @@
[cmr.common.cache :as cache]
[cmr.common.mime-types :as mt]
[cmr.common.services.errors :as svc-errors]
+ [cmr.transmit.token-denylist :as token-denylist]
[cmr.umm-spec.versioning :as umm-version]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@@ -129,10 +130,11 @@
(common-routes/search-response response))))
(defn log-search-result-metadata
- ([context hits concept-type total-took client-id token-type result-format param-str & param-args]
+ ([context hits concept-type total-took client-id token result-format param-str & param-args]
(let [metadata (meta context)
{shard-counts-atom :shard-counts} metadata
total-shard-count (apply + @shard-counts-atom)
search-count (count @shard-counts-atom)
- format-str (str "Found %d %ss in %d ms from client %s, token_type %s in format %s using %d Elasticsearch queries across %d shards " param-str)]
- (apply format format-str hits concept-type total-took client-id (get-token-type token-type) result-format search-count total-shard-count param-args))))
+ format-str (str "Found %d %ss in %d ms from client %s, token_type %s, token_hash %s in format %s using %d Elasticsearch queries across %d shards " param-str)]
+ (apply format format-str hits concept-type total-took client-id (get-token-type token)
+ (token-denylist/token-hash-for-log token) result-format search-count total-shard-count param-args))))
diff --git a/search-app/src/cmr/search/routes.clj b/search-app/src/cmr/search/routes.clj
index 0f68a5b7ef..6228bd2506 100644
--- a/search-app/src/cmr/search/routes.clj
+++ b/search-app/src/cmr/search/routes.clj
@@ -11,6 +11,7 @@
[cmr.common-app.api.request-context-user-augmenter :as context-augmenter]
[cmr.common-app.api.request-logger :as req-log]
[cmr.common-app.api.routes :as common-routes]
+ [cmr.common-app.api.token-denylist :as token-denylist]
[cmr.common-app.site.pages :as common-pages]
[cmr.common.api.context :as cmr-context]
[cmr.common.config :refer [defconfig]]
@@ -111,6 +112,7 @@
(defn handlers [system]
(-> (build-routes system)
+ token-denylist/deny-listed-token-handler
;; add-authentication-handler adds the token and client id for user to
;; the context add-user-id-and-sids-handler lazy adds the user id and
;; sids for that token Need to maintain this order (works backwards).
diff --git a/search-app/src/cmr/search/system.clj b/search-app/src/cmr/search/system.clj
index 6a24cc658b..e952790202 100644
--- a/search-app/src/cmr/search/system.clj
+++ b/search-app/src/cmr/search/system.clj
@@ -33,6 +33,7 @@
[cmr.search.services.query-execution.has-granules-results-feature :as hgrf]
[cmr.transmit.config :as transmit-config]
[cmr.transmit.launchpad-user-cache :as launchpad-user-cache]
+ [cmr.transmit.token-denylist :as token-denylist]
[cmr.transmit.urs :as urs]))
;; Design based on http://stuartsierra.com/2013/09/15/lifecycle-composition and related posts
@@ -115,6 +116,7 @@
acl/token-pc-cache-key (acl/create-token-pc-cache)
launchpad-user-cache/launchpad-user-cache-key (launchpad-user-cache/create-launchpad-user-cache)
urs/urs-cache-key (urs/create-urs-cache)
+ token-denylist/snapshot-cache-key (token-denylist/create-snapshot-cache)
kf/kms-cache-key (kf/create-kms-cache)
kl/kms-short-name-cache-key (kl/create-kms-short-name-cache)
kl/kms-umm-c-cache-key (kl/create-kms-umm-c-cache)
diff --git a/system-int-test/src/cmr/system_int_test/utils/index_util.clj b/system-int-test/src/cmr/system_int_test/utils/index_util.clj
index d313899be2..6bf2b3738e 100644
--- a/system-int-test/src/cmr/system_int_test/utils/index_util.clj
+++ b/system-int-test/src/cmr/system_int_test/utils/index_util.clj
@@ -24,14 +24,16 @@
(refresh-all-elastic-indexes))
(defn full-refresh-collection-granule-aggregate-cache
- "Triggers a full refresh of the collection granule aggregate cache in the indexer."
+ "Triggers a full refresh of the collection granule aggregate cache in the indexer and waits for
+ it to finish."
[]
(let [response (client/post
(url/full-refresh-collection-granule-aggregate-cache-url)
{:connection-manager (s/conn-mgr)
:headers {transmit-config/token-header (transmit-config/echo-system-token)}
:throw-exceptions false})]
- (is (= 200 (:status response)) (:body response))))
+ (is (= 200 (:status response)) (:body response))
+ (wait-until-indexed)))
(defn partial-refresh-collection-granule-aggregate-cache
"Triggers a partial refresh of the collection granule aggregate cache in the indexer."
diff --git a/system-int-test/test/cmr/system_int_test/search/collection/collection_temporal_search_test.clj b/system-int-test/test/cmr/system_int_test/search/collection/collection_temporal_search_test.clj
index 1c77c354f1..771c664fea 100644
--- a/system-int-test/test/cmr/system_int_test/search/collection/collection_temporal_search_test.clj
+++ b/system-int-test/test/cmr/system_int_test/search/collection/collection_temporal_search_test.clj
@@ -266,7 +266,6 @@
(index/wait-until-indexed)
;; Refresh the aggregate cache so that it includes all the granules that were added.
(index/full-refresh-collection-granule-aggregate-cache)
- (index/wait-until-indexed)
;; Reindex all the collections to get the latest information.
(ingest/reindex-all-collections)
diff --git a/transmit-lib/src/cmr/transmit/token_denylist.clj b/transmit-lib/src/cmr/transmit/token_denylist.clj
new file mode 100644
index 0000000000..60dd2308ed
--- /dev/null
+++ b/transmit-lib/src/cmr/transmit/token_denylist.clj
@@ -0,0 +1,224 @@
+(ns cmr.transmit.token-denylist
+ "Tokens and users blocked from CMR. Entries live in a Redis hash shared by all applications.
+ Each instance checks requests against a snapshot of the hash that it reloads every
+ token-denylist-refresh-seconds, keeping the last good snapshot when Redis is unavailable."
+ (:require
+ [cheshire.core :as json]
+ [clojure.string :as string]
+ [cmr.common.cache :as cache]
+ [cmr.common.cache.in-memory-cache :as mem-cache]
+ [cmr.common.config :refer [defconfig]]
+ [cmr.common.hash-cache :as hash-cache]
+ [cmr.common.log :refer [error info warn]]
+ [cmr.common.util :as common-util]
+ [cmr.redis-utils.config :as redis-config]
+ [cmr.redis-utils.redis-hash-cache :as redis-hash-cache]
+ [cmr.transmit.config :as transmit-config]
+ [cmr.transmit.tokens :as tokens])
+ (:import
+ (java.util.concurrent TimeUnit)
+ (java.util.concurrent.locks ReentrantLock)
+ (org.apache.commons.codec.digest DigestUtils)))
+
+(def entry-types
+ "Deny list entries block either one token, by its hash, or every token of a user."
+ #{:token :user})
+
+(def denylist-key
+ "The Redis hash holding deny list entries."
+ :token-denylist)
+
+(def snapshot-cache-key
+ "The cache key for this instance's snapshot of the deny list."
+ :token-denylist-snapshot)
+
+(declare token-denylist-refresh-seconds)
+(defconfig token-denylist-refresh-seconds
+ "How often each instance reloads the token deny list from Redis."
+ {:default 30 :type Long})
+
+(defn create-snapshot-cache
+ "Creates the cache holding this instance's snapshot of the deny list."
+ []
+ (mem-cache/create-in-memory-cache))
+
+(defn token-hash
+ "Returns the SHA-256 hex digest identifying the token. For an EDL JWT only the signed header and
+ payload are hashed, so every form of the token that passes signature verification hashes the
+ same, however the signature is encoded."
+ [token]
+ (let [token (string/trim (tokens/bearer-stripped token))
+ [header payload signature] (string/split token #"\." 3)
+ signed (when (and signature
+ (re-matches #"[A-Za-z0-9=_-]+" header)
+ (re-matches #"[A-Za-z0-9=_-]+" payload))
+ (str header "." payload))
+ ;; Classified by the signed part alone, whatever the signature holds. The anchored checks
+ ;; above keep is-jwt-token?'s unanchored regex linear; it also throws on some bad headers.
+ jwt? (and signed (try (common-util/is-jwt-token? (str signed ".x")) (catch Exception _ false)))]
+ (DigestUtils/sha256Hex ^String (if jwt? signed token))))
+
+(defn token-hash-for-log
+ "The token's hash for log lines, or nil for no token or the system token."
+ [token]
+ (when (and token (not (transmit-config/echo-system-token? token)))
+ (token-hash token)))
+
+(defn- field
+ [entry-type id]
+ (str (name entry-type) ":" id))
+
+(defn- parse-field
+ [f]
+ (let [[entry-type id] (string/split f #":" 2)
+ entry-type (keyword entry-type)]
+ (when (and (seq id) (entry-types entry-type))
+ [entry-type id])))
+
+(defn- store
+ []
+ ;; keys-to-track is left empty so /caches/clear-cache never wipes the list.
+ (redis-hash-cache/create-redis-hash-cache
+ {:read-connection (redis-config/redis-read-conn-opts)
+ :primary-connection (redis-config/redis-conn-opts)}))
+
+(defn- parse-metadata
+ [v]
+ (try
+ (json/parse-string v true)
+ (catch Exception _ {})))
+
+(defn get-entries
+ "Returns the deny list as {:token {hash metadata} :user {user-id metadata}}."
+ []
+ (reduce-kv (fn [entries f v]
+ (if-let [[entry-type id] (parse-field f)]
+ (assoc-in entries [entry-type id] (parse-metadata v))
+ entries))
+ {:token {} :user {}}
+ (or (hash-cache/get-map (store) denylist-key) {})))
+
+(defn add-entry!
+ "Adds or replaces a deny list entry."
+ [entry-type id metadata]
+ (hash-cache/set-value (store) denylist-key (field entry-type id) (json/generate-string metadata)))
+
+(defn remove-entry!
+ "Removes a deny list entry. Returns true if it existed."
+ [entry-type id]
+ (pos? (or (hash-cache/remove-value (store) denylist-key (field entry-type id)) 0)))
+
+(def ^:private empty-snapshot
+ {:token #{} :user #{}})
+
+(defn- load-snapshot
+ []
+ (reduce (fn [snapshot f]
+ (if-let [[entry-type id] (parse-field f)]
+ (update snapshot entry-type conj (if (= :user entry-type) (string/lower-case id) id))
+ snapshot))
+ empty-snapshot
+ (hash-cache/get-keys (store) denylist-key)))
+
+(defn- now-ms
+ []
+ ;; Monotonic, so wall clock changes can't stop refreshes.
+ (quot (System/nanoTime) 1000000))
+
+(defn- fresh?
+ [{:keys [expires-at]}]
+ (and expires-at (< (now-ms) expires-at)))
+
+(defonce ^:private ^ReentrantLock refresh-lock (ReentrantLock.))
+
+;; Survives /caches/clear-cache so a reset during a Redis outage doesn't drop the list.
+(defonce ^:private last-loaded (atom nil))
+
+(def ^:private first-load-wait-ms
+ "How long a request waits for an instance's first load of the list before going unchecked."
+ 500)
+
+(defn- entry-count
+ [snapshot]
+ (+ (count (:token snapshot)) (count (:user snapshot))))
+
+(defn- log-change
+ [previous loaded]
+ (when (not= previous loaded)
+ (let [msg (format "Token deny list now has %d token and %d user entries, previously %d."
+ (count (:token loaded)) (count (:user loaded)) (entry-count previous))]
+ (if (< (entry-count loaded) (entry-count previous))
+ (warn msg)
+ (info msg)))))
+
+(defn- refresh!
+ [snapshot-cache]
+ (let [cached (cache/get-value snapshot-cache :snapshot)]
+ (if (fresh? cached)
+ (:entries cached)
+ (let [previous (or (:entries cached) @last-loaded)
+ entries (try
+ (let [loaded (load-snapshot)]
+ (log-change previous loaded)
+ (reset! last-loaded loaded))
+ (catch Exception e
+ (error (if @last-loaded
+ "Unable to reload the token deny list, keeping the previous copy:"
+ "Unable to load the token deny list, allowing all tokens until it loads:")
+ (.getMessage e))
+ (or previous empty-snapshot)))]
+ (cache/set-value snapshot-cache :snapshot
+ {:entries entries
+ :expires-at (+ (now-ms) (* 1000 (token-denylist-refresh-seconds)))})
+ entries))))
+
+(defn- current-snapshot
+ "Returns this instance's snapshot, reloading it from Redis once it is older than the refresh
+ interval. While one request reloads, others keep using the previous snapshot. Before the first
+ load, requests wait up to first-load-wait-ms for it. A failed reload keeps the previous
+ snapshot."
+ [snapshot-cache]
+ (let [cached (cache/get-value snapshot-cache :snapshot)
+ previous (or (:entries cached) @last-loaded)]
+ (cond
+ (fresh? cached) (:entries cached)
+
+ previous (if (.tryLock refresh-lock)
+ (try
+ (refresh! snapshot-cache)
+ (finally (.unlock refresh-lock)))
+ previous)
+
+ (.tryLock refresh-lock first-load-wait-ms TimeUnit/MILLISECONDS)
+ (try
+ (refresh! snapshot-cache)
+ (finally (.unlock refresh-lock)))
+
+ :else empty-snapshot)))
+
+(defn reload-snapshot
+ "Makes the next request on this instance read the deny list from Redis."
+ [context]
+ (when-let [snapshot-cache (cache/context->cache context snapshot-cache-key)]
+ (when-let [cached (cache/get-value snapshot-cache :snapshot)]
+ (cache/set-value snapshot-cache :snapshot (assoc cached :expires-at nil)))))
+
+(defn user-denied?
+ "Returns true if the user id is on the deny list."
+ [context user-id]
+ (boolean
+ (when-let [snapshot-cache (cache/context->cache context snapshot-cache-key)]
+ (contains? (:user (current-snapshot snapshot-cache)) (some-> user-id string/lower-case)))))
+
+(defn denied?
+ "Returns true if the token, or the user it belongs to, is on the deny list. user-id-fn is
+ only called when users are listed, and if it throws the exception propagates so the request
+ fails rather than going unchecked. User ids match case-insensitively."
+ [context token user-id-fn]
+ (when-let [snapshot-cache (cache/context->cache context snapshot-cache-key)]
+ (let [{tokens :token users :user} (current-snapshot snapshot-cache)]
+ (boolean
+ (or (and (seq tokens)
+ (contains? tokens (token-hash token)))
+ (and (seq users)
+ (contains? users (some-> (user-id-fn) string/lower-case))))))))
diff --git a/transmit-lib/src/cmr/transmit/tokens.clj b/transmit-lib/src/cmr/transmit/tokens.clj
index bbfb6a63c4..9ee50954fe 100644
--- a/transmit-lib/src/cmr/transmit/tokens.clj
+++ b/transmit-lib/src/cmr/transmit/tokens.clj
@@ -20,12 +20,17 @@
(def edl-assurance-level-edl-mfa 4)
(def edl-assurance-level-launchpad-piv 5)
+(defn bearer-stripped
+ "Returns the token as JWT verification sees it. The deny list hashes this same string."
+ [token]
+ (string/replace token #"Bearer\W+" ""))
+
(defn get-jwt-claims
"Extracts claims from a JWT token. Returns nil if invalid."
[token]
(try
(let [public-key (buddy-keys/jwk->public-key (json/parse-string (transmit-config/edl-public-key) true))
- bearer-stripped-token (string/replace token #"Bearer\W+" "")]
+ bearer-stripped-token (bearer-stripped token)]
(jwt/unsign bearer-stripped-token public-key {:alg :rs256}))
(catch Exception _e
nil)))
@@ -53,7 +58,7 @@
[token]
(try
(let [public-key (buddy-keys/jwk->public-key (json/parse-string (transmit-config/edl-public-key) true))
- bearer-stripped-token (string/replace token #"Bearer\W+" "")
+ bearer-stripped-token (bearer-stripped token)
decrypted-token (jwt/unsign bearer-stripped-token public-key {:alg :rs256})]
(:uid decrypted-token))
(catch clojure.lang.ExceptionInfo ex
diff --git a/transmit-lib/test/cmr/transmit/test/token_denylist.clj b/transmit-lib/test/cmr/transmit/test/token_denylist.clj
new file mode 100644
index 0000000000..88fdcb0bc1
--- /dev/null
+++ b/transmit-lib/test/cmr/transmit/test/token_denylist.clj
@@ -0,0 +1,71 @@
+(ns cmr.transmit.test.token-denylist
+ (:require
+ [clojure.test :refer [deftest is testing use-fixtures]]
+ [cmr.common.hash-cache :as hash-cache]
+ [cmr.transmit.config]
+ [cmr.transmit.token-denylist :as denylist])
+ (:import
+ (java.util Base64)
+ (org.apache.commons.codec.digest DigestUtils)))
+
+(use-fixtures :each (fn [f]
+ (reset! @#'denylist/last-loaded nil)
+ (f)))
+
+;; Protocol functions are called directly on records, so the store is replaced instead.
+(defmacro ^:private with-fields
+ [fields-fn & body]
+ `(with-redefs [cmr.transmit.token-denylist/store
+ (constantly (reify hash-cache/CmrHashCache
+ (get-keys [_# _#] (~fields-fn))))]
+ ~@body))
+
+(defn- context
+ []
+ {:system {:caches {denylist/snapshot-cache-key (denylist/create-snapshot-cache)}}})
+
+(def ^:private token "opaque-launchpad-style-token-value")
+
+(def ^:private token-field (str "token:" (DigestUtils/sha256Hex token)))
+
+(def ^:private edl-header
+ (.encodeToString (.withoutPadding (Base64/getUrlEncoder))
+ (.getBytes "{\"typ\":\"JWT\",\"origin\":\"Earthdata Login\",\"alg\":\"RS256\"}")))
+
+;; Sample token, safe for use in tests: a made-up header and the payload {"uid":"u1"}, never signed.
+(def ^:private signed (str edl-header ".eyJ1aWQiOiJ1MSJ9"))
+
+(deftest token-hash-test
+ (is (= (DigestUtils/sha256Hex token) (denylist/token-hash token) (denylist/token-hash (str "Bearer " token))))
+ (testing "an EDL JWT hashes its signed header and payload, so signature variants can't escape"
+ (is (= (DigestUtils/sha256Hex signed)
+ (denylist/token-hash (str signed ".QQ"))
+ (denylist/token-hash (str signed ".QR"))
+ (denylist/token-hash (str signed ".AABB"))
+ (denylist/token-hash (str "Bearer " signed ".QQ"))
+ (denylist/token-hash (str signed ".QQBearer-"))
+ (denylist/token-hash (str signed ".QQBearer "))
+ (denylist/token-hash (str signed ".QQBearer\n"))
+ (denylist/token-hash (str signed ".!Bearer.Bearer.Bearer-QQ")))))
+ (testing "the system token is never logged"
+ (is (nil? (denylist/token-hash-for-log (cmr.transmit.config/echo-system-token))))))
+
+(deftest denied-test
+ (with-fields (constantly [token-field "user:User1"])
+ (let [ctx (context)]
+ (is (true? (denylist/denied? ctx token (constantly "other"))))
+ (is (true? (denylist/denied? ctx "other-token" (constantly "USER1"))))
+ (is (false? (denylist/denied? ctx "other-token" (constantly "other"))))
+ (is (true? (denylist/user-denied? ctx "USER1")))
+ (testing "a failed user lookup fails the request"
+ (is (thrown? Exception (denylist/denied? ctx "other-token" #(throw (Exception. "EDL down")))))))))
+
+(deftest redis-failure-keeps-last-loaded-test
+ (let [clock (atom 0)]
+ (with-redefs [cmr.transmit.token-denylist/now-ms #(deref clock)]
+ (let [ctx (context)]
+ (with-fields (constantly [token-field])
+ (is (true? (denylist/denied? ctx token (constantly nil)))))
+ (swap! clock + (* 1000 (inc (denylist/token-denylist-refresh-seconds))))
+ (with-fields #(throw (Exception. "connection refused"))
+ (is (true? (denylist/denied? ctx token (constantly nil)))))))))