Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions access-control-app/docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -789,6 +793,50 @@ Content-Type: application/json

["s3://aws.example-2.com","s3://aws.example-3.com"]
```

## <a name="token-denylist"></a> 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

### <a name="list-token-denylist"></a> 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"}]}
```

### <a name="add-token-denylist"></a> Deny a Token or User

`PUT /token-denylist/tokens/<sha256>` or `PUT /token-denylist/users/<user-id>`. 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"}
```

### <a name="remove-token-denylist"></a> 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
```

## <a name="health"></a> Health

### <a name="application-health"></a> Application Health
Expand Down
3 changes: 3 additions & 0 deletions access-control-app/src/cmr/access_control/api/routes.clj
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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}
Expand Down
2 changes: 2 additions & 0 deletions access-control-app/src/cmr/access_control/routes.clj
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]]
Expand Down Expand Up @@ -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,
Expand Down
6 changes: 5 additions & 1 deletion access-control-app/src/cmr/access_control/system.clj
Original file line number Diff line number Diff line change
Expand Up @@ -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]]
Expand All @@ -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)
Expand Down Expand Up @@ -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))

Expand Down
151 changes: 151 additions & 0 deletions common-app-lib/src/cmr/common_app/api/token_denylist.clj
Original file line number Diff line number Diff line change
@@ -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)))))
56 changes: 56 additions & 0 deletions common-app-lib/test/cmr/common_app/test/api/token_denylist.clj
Original file line number Diff line number Diff line change
@@ -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]}"))}))))))))
Loading