LCOV - code coverage report
Current view: top level - matchscore/access - core.clj Coverage Total Hit
Test: lcov.info Lines: 94.1 % 119 112
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.access.core
       2              :   "Access-control API on top of the jcasbin Enforcer.
       3              : 
       4              :   Read API : `allowed?`, `authorize!`, `list-policies`,
       5              :              `list-grouping-policies`.
       6              :   Write API: `add-policy!`, `remove-policy!`. Policy writes propagate to peer
       7              :              JVMs via `access.watcher/publish-reload!`.
       8              : 
       9              :   Casbin grouping rows are legacy only; application roles are carried in the
      10              :   request object as global/resource role attributes."
      11              :   (:require
      12              :    [camel-snake-kebab.core :as csk]
      13              :    [clojure.string :as str]
      14              :    [matchscore.access.watcher :as access-watcher]
      15              :    [matchscore.domain.event.entity :as event-entity]
      16              :    [taoensso.telemere :as t])
      17              :   (:import
      18              :    (java.util               HashMap)
      19              :    (org.casbin.jcasbin.main Enforcer)))
      20              : 
      21              : 
      22            4 : (defn- ->-obj-map
      23              :   "Coerces a Clojure obj-map into a java.util.HashMap<String,Object>
      24              :   with snake_case string keys, which is what the Casbin matcher expects
      25              :   when evaluating `r.obj.<attr>`.
      26              : 
      27              :   Nested Clojure colls (maps, sets, vectors, lists) are coerced too:
      28              :   - maps → HashMap with snake_case string keys
      29              :   - role vectors under :global-roles/:participant-roles → pipe-delimited string
      30              :     for legacy policy compatibility
      31              :   - other sets/vectors/lists → java.util.ArrayList"
      32              :   ^HashMap [obj-map]
      33            8 :   (let [hm (HashMap.)]
      34          104 :     (doseq [[k v] obj-map]
      35           32 :       (let [k* (if (keyword? k) (csk/->snake_case_string k) (str k))
      36           72 :             v* (cond (and (#{"global_roles" "participant_roles"} k*) (sequential? v))
      37           67 :                      (str "|" (str/join "|" (map #(if (keyword? %) (name %) %) v)) "|")
      38              : 
      39           15 :                      (map? v) (->-obj-map v)
      40              : 
      41           12 :                      (set? v)
      42            1 :                      (java.util.ArrayList.
      43           11 :                       ^java.util.Collection (mapv #(if (keyword? %) (name %) %) v))
      44              : 
      45           12 :                      (sequential? v)
      46            1 :                      (java.util.ArrayList.
      47           11 :                       ^java.util.Collection (mapv #(if (keyword? %) (name %) %) v))
      48              : 
      49           15 :                      (keyword? v) (name v)
      50              : 
      51            4 :                      :else v)]
      52           12 :         (.put hm k* v*)))
      53            4 :     hm))
      54              : 
      55              : 
      56            4 : (defn- ->-action
      57              :   [action]
      58           29 :   (cond (keyword? action) (name action)
      59            3 :         :else             (str action)))
      60              : 
      61              : 
      62            4 : (defn- ->-sub
      63              :   [user-uuid]
      64           27 :   (cond (nil? user-uuid)    nil
      65           16 :         (string? user-uuid) user-uuid
      66            3 :         :else               (str user-uuid)))
      67              : 
      68              : 
      69            4 : (defn- ->-dom
      70              :   [domain]
      71           27 :   (cond (nil? domain)     "*"
      72           16 :         (string? domain)  domain
      73            6 :         (keyword? domain) (name domain)
      74            3 :         :else             (str domain)))
      75              : 
      76              : 
      77            4 : (defn- imported-event-write?
      78              :   [obj-map action]
      79           34 :   (and
      80           20 :    (= "event" (:type obj-map))
      81           12 :    (event-entity/read-only? obj-map)
      82            4 :    (not= "read" (->-action action))))
      83              : 
      84              : 
      85            4 : (defn allowed?
      86              :  "Evaluates one access decision. Returns true iff the enforcer allows
      87              :   `action` on `obj-map` for `user-uuid` in `domain`.
      88              : 
      89              :   - `enforcer`  : the jcasbin Enforcer (from `(:enforcer casbin)` or
      90              :                   request `:ctx :enforcer`)
      91              :   - `user-uuid` : caller UUID (string)
      92              :   - `domain`    : currently always \"*\"
      93              :   - `obj-map`   : Clojure map with at least :type plus any attributes the
      94              :                   policy `cond` references (e.g. :owner-id, :participant-roles)
      95              :   - `action`    : keyword or string (kebab-case)"
      96              :  [enforcer user-uuid domain obj-map action]
      97           21 :  (when (nil? enforcer)
      98            7 :    (throw (ex-info "Casbin enforcer is not initialized" {:type :access/no-enforcer})))
      99           16 :  (let [sub (->-sub user-uuid)
     100           12 :        dom (->-dom domain)
     101           12 :        obj (->-obj-map obj-map)
     102           12 :        act (->-action action)]
     103           29 :    (cond (imported-event-write? obj-map action) false
     104              : 
     105           16 :          (nil? sub)
     106            4 :          (do
     107           44 :            (t/log!
     108              :             :debug
     109            0 :             {:message "Access denied: no user-uuid"
     110            0 :              :domain  dom
     111            0 :              :obj     obj-map
     112            0 :              :action  act})
     113              :            false)
     114              : 
     115           28 :          :else (.enforce ^Enforcer enforcer (object-array [sub dom obj act])))))
     116              : 
     117              : 
     118            4 : (defn authorize!
     119              :  "Like `allowed?` but throws `:api-forbidden` on deny.
     120              : 
     121              :   `ctx` is the per-request map (from `:ctx` on a Ring request or the
     122              :   realtime event ctx). It must carry `:enforcer` (set by `wrap-components`
     123              :   / sente-router) and the call site provides `user-uuid` either by
     124              :   passing it as the second positional arg or via `(:user/uuid auth-headers)`."
     125              :  ([ctx user-uuid domain obj-map action]
     126           16 :   (let [enforcer (:enforcer ctx)]
     127           36 :     (if (allowed? enforcer user-uuid domain obj-map action)
     128              :       true
     129            4 :       (throw
     130            8 :        (ex-info
     131           25 :         (if (imported-event-write? obj-map action) "Imported events are read-only" "Forbidden")
     132           32 :         {:type        :api-forbidden
     133           22 :          :message-key (when (imported-event-write? obj-map action) :event/imported-read-only)
     134            4 :          :user-uuid   user-uuid
     135            4 :          :domain      domain
     136            4 :          :obj         obj-map
     137            4 :          :action      action}))))))
     138              : 
     139              : 
     140              : ;; ---------------------------------------------------------------------------
     141              : ;; Mutation API (PR3)
     142              : ;;
     143              : ;; Each mutation: (1) calls the underlying jcasbin write method, which
     144              : ;; persists through the JDBCAdapter, then (2) publishes on the reload
     145              : ;; channel so peer JVMs reload within ~100 ms. The publisher itself does
     146              : ;; NOT pre-emptively reload — jcasbin already updates the in-process
     147              : ;; cache as part of the write call, and the watcher will pick up the
     148              : ;; pub/sub message we just published.
     149              : ;; ---------------------------------------------------------------------------
     150              : 
     151              : 
     152            4 : (defn- ctx->-parts
     153              :   "Pulls the bits the mutation API needs out of the per-request `ctx` (or
     154              :   a synthetic ctx in tests). Both forms are tolerated:
     155              : 
     156              :   - ctx with :enforcer + :casbin + :redis  (typical request ctx)
     157              :   - ctx with only :casbin (component map)  (REPL / job)"
     158              :   [ctx]
     159           17 :   (let [casbin   (or (:casbin ctx) ctx)
     160           17 :         enforcer (or (:enforcer ctx) (:enforcer casbin))
     161           18 :         redis    (or (:redis casbin) (:redis ctx))
     162           15 :         channel  (or (:reload-channel casbin) "casbin:policy:reload")]
     163           11 :     (when (nil? enforcer)
     164            7 :       (throw (ex-info "Casbin enforcer is not initialized" {:type :access/no-enforcer})))
     165           10 :     {:enforcer enforcer
     166            2 :      :redis    redis
     167            2 :      :channel  channel}))
     168              : 
     169              : 
     170            4 : (defn- -publish-if-redis
     171              :   "Call `publish-reload!` only when we have a Redis client. In single-JVM
     172              :   test setups the caller may pass a ctx without :redis."
     173              :   [redis channel]
     174            5 :   (when redis
     175            1 :     (try
     176            4 :       (access-watcher/publish-reload! redis channel)
     177              :       (catch Exception e
     178            0 :         (t/log!
     179              :          :warn
     180            0 :          {:message   "Failed to publish Casbin reload"
     181            0 :           :exception e})))))
     182              : 
     183              : 
     184            4 : (defn add-role-for-user-in-domain!
     185              :  "Legacy grouping mutation. Disabled because application roles now live in
     186              :   users.roles and resource participant rows."
     187              :  [_ctx user-uuid role domain]
     188            1 :  (throw
     189            3 :   (ex-info
     190              :    "Casbin grouping rows are not used for application roles"
     191            6 :    {:type      :access/grouping-disabled
     192            1 :     :user-uuid user-uuid
     193            1 :     :role      role
     194            1 :     :domain    domain})))
     195              : 
     196              : 
     197            4 : (defn remove-role-for-user-in-domain!
     198              :  [_ctx user-uuid role domain]
     199            1 :  (throw
     200            3 :   (ex-info
     201              :    "Casbin grouping rows are not used for application roles"
     202            6 :    {:type      :access/grouping-disabled
     203            1 :     :user-uuid user-uuid
     204            1 :     :role      role
     205            1 :     :domain    domain})))
     206              : 
     207              : 
     208            4 : (defn add-policy!
     209              :  "Add a policy row. `cond-expr` defaults to \"true\", `eft` to \"allow\"."
     210            9 :  ([ctx role domain obj-type action] (add-policy! ctx role domain obj-type action "true" "allow"))
     211              :  ([ctx role domain obj-type action cond-expr eft]
     212            8 :   (let [{:keys [enforcer redis channel]} (ctx->-parts ctx)
     213            2 :         added (.addPolicy
     214              :                ^Enforcer enforcer
     215           20 :                (into-array String [role domain obj-type action cond-expr eft]))]
     216            8 :     (-publish-if-redis redis channel)
     217            2 :     added)))
     218              : 
     219              : 
     220            4 : (defn remove-policy!
     221            9 :  ([ctx role domain obj-type action] (remove-policy! ctx role domain obj-type action "true" "allow"))
     222              :  ([ctx role domain obj-type action cond-expr eft]
     223            8 :   (let [{:keys [enforcer redis channel]} (ctx->-parts ctx)
     224            2 :         removed (.removePolicy
     225              :                  ^Enforcer enforcer
     226           20 :                  (into-array String [role domain obj-type action cond-expr eft]))]
     227            8 :     (-publish-if-redis redis channel)
     228            2 :     removed)))
     229              : 
     230              : 
     231              : ;; ---------------------------------------------------------------------------
     232              : ;; Reads (in-memory cache; no DB round trip)
     233              : ;; ---------------------------------------------------------------------------
     234              : 
     235              : 
     236           20 : (defn- ->-vec [x] (when x (mapv vec (java.util.ArrayList. ^java.util.Collection x))))
     237              : 
     238              : 
     239            4 : (defn roles-for-user-in-domain
     240              :  "Legacy grouping read. Always empty; use users.roles / participant roles."
     241              :  [_ctx _user-uuid _domain]
     242            1 :  [])
     243              : 
     244              : 
     245            4 : (defn users-for-role-in-domain
     246              :  [_ctx _role _domain]
     247            1 :  [])
     248              : 
     249              : 
     250            4 : (defn list-policies
     251              :  "Returns every `p` row in the enforcer as a vector of vectors:
     252              :   [[sub dom obj-type act cond eft] ...]."
     253              :  [ctx]
     254           14 :  (let [{:keys [enforcer]} (ctx->-parts ctx)] (->-vec (.getPolicy ^Enforcer enforcer))))
     255              : 
     256              : 
     257            4 : (defn list-grouping-policies
     258              :  "Legacy grouping read. Always empty; Casbin `g` rows are not app roles."
     259              :  [_ctx]
     260            1 :  [])
     261              : 
     262              : 
     263            4 : (defn list-assignments-for-user
     264              :  "Cross-section of `list-grouping-policies` filtered to the given user."
     265              :  [ctx user-uuid]
     266            6 :  (filterv #(= user-uuid (first %)) (list-grouping-policies ctx)))
        

Generated by: LCOV version 2.0-1